python连接mysql数据库,并做增删查改操作
import pymysql # 导入数据库模块 # 创建一个数据库对象,利用connect进行连接数据库 try: db = pymysql.connect(host='localhost', # ip地址 database='demo1', # 帐套名 user='root', # 数据库账号 password='123456', # 密码 port=3306 # 端口号 ) except: print('连接mysql数据库失败!') else: # 创建一个游标对象 游标:可以执行sql语句,执行完sql语句有返回值 cursor = db.cursor() # 创建一个游标对象 # 查询 sql_select = 'select * from student0;' # 创建一条查询语句 cursor.execute(sql_select) # 执行sql语句 # all = cursor.fetchall() #用变量名all来接收游标返回的所有内容 one = cursor.fetchone() # 用变量名one来接收游标返回的一条内容 # print(all) print(one) #新增 sql_insert = 'insert into student0(id,name,class) value(7,"小明",3)' # 创建一条插入语句 cursor.execute(sql_insert) # 执行sql语句 db.commit() # 确认 修改表内容后需要做确认操作 #修改 sql_update = 'update student0 set name="小发" where id = 7' #创建一条修改语句 cursor.execute(sql_update) # 执行sql语句 db.commit() #确认 #删除 sql_delete = 'delete from student0 where id = 7' #创建一条删除语句 cursor.execute(sql_delete) # 执行sql语句 db.commit() #确认
本文来自博客园,作者:夏夏夏天的西瓜,转载请注明原文链接:https://www.cnblogs.com/qiang6313669/p/15096672.html

浙公网安备 33010602011771号