python创建表
''' python代码里操作mysql 1. 首先需要安装mysql服务器 2. 其次是安装mysqlclient: pip install mysqlclient 3. 导入模块 MysqlSQLdb : import MysqlSQLdb 4. 创建连接 conn = MysqlSQLdb.connect(host='127.0.0.1',port=3306,user='root',password='password',db='cmdb') 5. 获取连接的游标,只有获取了cursor, 我们才能进行各种操作. cursor = conn.cursor() 6. 执行sql (DQL 和 DML) : cursor.execute('select * from table') 7. 获取上一个查询的结果,是单个结果: data = cursor.fetchone() 使用fetchall 函数,将结果集(多维元组)存入rows 里面 rows = cursor.fetchall() DML提交: conn.commit() #依次遍历结果集,发现每个元素,就是表中的一条记录,用一个元组来显示 for row in rows: print row 8. 关闭游标 : cursor.close() 9. 关闭连接 : conn.close() ''' import MySQLdb try: # 创建一个数据库连接对象 conn = MySQLdb.connect( host='localhost', port=3306, user='root', password='123456', database='TestDB' ) # 获取连接的游标 cursor = conn.cursor() # 执行语句,创建数据库TestDB sql1 = '''drop table if exists student_info; create table student_info( sno varchar(10) primary key , sname varchar(10), sage int(3), ssex char(1), school varchar(10), class varchar(10), address varchar(20) )engine = Innodb default charset = utf8mb4 comment='学生表'; ''' cursor.execute(sql1) # 执行语句,展示该数据库中的所有表 sql2 = 'show tables;' cursor.execute(sql2) for table in cursor: print(table) # 关闭游标 cursor.close() # 关闭连接 conn.close() except BaseException as e: print(f'连接数据库失败,失败信息:{e}')''' python代码里操作mysql 1. 首先需要安装mysql服务器 2. 其次是安装mysqlclient: pip install mysqlclient 3. 导入模块 MysqlSQLdb : import MysqlSQLdb 4. 创建连接 conn = MysqlSQLdb.connect(host='127.0.0.1',port=3306,user='root',password='password',db='cmdb') 5. 获取连接的游标,只有获取了cursor, 我们才能进行各种操作. cursor = conn.cursor() 6. 执行sql (DQL 和 DML) : cursor.execute('select * from table') 7. 获取上一个查询的结果,是单个结果: data = cursor.fetchone() 使用fetchall 函数,将结果集(多维元组)存入rows 里面 rows = cursor.fetchall() DML提交: conn.commit() #依次遍历结果集,发现每个元素,就是表中的一条记录,用一个元组来显示 for row in rows: print row 8. 关闭游标 : cursor.close() 9. 关闭连接 : conn.close() ''' import MySQLdb try: # 创建一个数据库连接对象 conn = MySQLdb.connect( host='localhost', port=3306, user='root', password='123456', database='TestDB' ) # 获取连接的游标 cursor = conn.cursor() # 执行语句,创建数据库TestDB sql1 = '''drop table if exists student_info; create table student_info( sno varchar(10) primary key , sname varchar(10), sage int(3), ssex char(1), school varchar(10), class varchar(10), address varchar(20) )engine = Innodb default charset = utf8mb4 comment='学生表'; ''' cursor.execute(sql1) # 执行语句,展示该数据库中的所有表 sql2 = 'show tables;' cursor.execute(sql2) for table in cursor: print(table) # 关闭游标 cursor.close() # 关闭连接 conn.close() except BaseException as e: print(f'连接数据库失败,失败信息:{e}')
结果:
('student_info',)
钟声敲响了日落,柏油路跃过山坡,一直通向北方的是我们想象,长大后也未曾经过~
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY