使用python3.6操作mysql

JensYue 2019-10-13 02:27:49
#coding:utf-8 #python3.6使用pymysql操作mysql print("=====================mysql数据库=====================") import pymysql.cursors # 连接数据库 connect = pymysql.Connect( host='127.0.0.1', port=3306, user='root', passwd='19910101a', db='note', charset='utf8' ) # 获取游标 cursor = connect.cursor() #删除表 sql = 'DROP TABLE IF EXISTS student' cursor.execute(sql) connect.commit() print('如果存在表就删除表格') #创建表格 sql = "CREATE TABLE student(id INTEGER PRIMARY KEY,name TEXT)" try: cursor.execute(sql) connect.commit() except: print("表已存在") print('成功创建表格') # 插入数据 sql = "INSERT INTO student VALUES(%d,'%s')" data = (1, 'student1') cursor.execute(sql % data) connect.commit() print('成功插入', cursor.rowcount, '条数据') # 查询数据方法2,注意这种方式会自动帮你添加引号 sql = "INSERT INTO student VALUES(%s,%s)" data = (1, 'student1') cursor.execute(sql, data) connect.commit() print('成功插入', cursor.rowcount, '条数据') # 修改数据 sql = "UPDATE student SET name = '%s' WHERE id = %d " data = ('student2', 1) cursor.execute(sql % data) connect.commit() print('成功修改', cursor.rowcount, '条数据') # 查询数据 sql = "SELECT * FROM student WHERE id=%d" data = (1,) cursor.execute(sql % data) for row in cursor.fetchall(): print("%s" % str(row)) print('共查找出', cursor.rowcount, '条数据') # 删除数据 sql = "DELETE FROM student WHERE id = %d LIMIT %d" data = (1, 1) cursor.execute(sql % data) connect.commit() print('成功删除', cursor.rowcount, '条数据') # 事务处理 sql_1 = "UPDATE student SET name = name + '1' WHERE id = 1 " try: cursor.execute(sql_1) except Exception as e: connect.rollback() # 事务回滚 print('事务处理失败', e) else: connect.commit() # 事务提交 print('事务处理成功', cursor.rowcount) # 关闭连接 cursor.close() connect.close() #pymysql.Connect()参数说明 #host(str): MySQL服务器地址 #port(int): MySQL服务器端口号 #user(str): 用户名 #passwd(str): 密码 #db(str): 数据库名称 #charset(str): 连接编码 # #connection对象支持的方法 #cursor() 使用该连接创建并返回游标 #commit() 提交当前事务 #rollback() 回滚当前事务 #close() 关闭连接 # #cursor对象支持的方法 #execute(op) 执行一个数据库的查询命令 #fetchone() 取得结果集的下一行 #fetchmany(size) 获取结果集的下几行 #fetchall() 获取结果集中的所有行 #rowcount() 返回数据条数或影响行数 #close() 关闭游标对象
...全文
26 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

433

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧