pymysql库
import pymysql.cursors # 连接数据库 connect = pymysql.Connect( host=‘192.168.0.250‘, port=3306, user=‘root‘, passwd=‘123456‘, db=‘anec‘, charset=‘utf8‘ ) # 获取游标 cursor = connect.cursor() # 创建数据表,执行SQL语句 create_table = """ create table t1( id int , name varchar(255) ) """ cursor.execute(create_table) # 添加数据,并需要commit提交 add_t1 = """ insert into t1(id,name) values(1,‘小红‘),(2,‘小美‘);""" cursor.execute(add_t1) connect.commit() # 格式化,插入单条数据 sql = ‘insert into userinfo (user,pwd) values (%s,%s);‘ name = ‘wuli‘ pwd = ‘123456789‘ cursor.execute(sql, [name, pwd]) connect.commit() # 获取最新的那一条数据的ID last_id = cursor.lastrowid print("最后一条数据的ID是:", last_id) # 定义要执行的sql语句,拼接并执行sql语句 sql = ‘insert into userinfo(user,pwd) values(%s,%s);‘ data = [ (‘july‘, ‘147‘), (‘june‘, ‘258‘), (‘marin‘, ‘369‘)] cursor.executemany(sql, data) # 删除数据,拼接并执行SQL语句 sql = "delete from userinfo where user=%s;" name = "june" cursor.execute(sql, [name]) connect.commit() # 拼接并执行SQL语句,修改数据 sql = "update userinfo set pwd=%s where user=%s;" cursor.execute(sql, ["july", "july"]) connect.commit() # 获取一个光标,定义将要执行的sql语句,拼接并执行sql语句,取到查询结果 cursor = connect.cursor(cursor=pymysql.cursors.DictCursor) # 返回字典数据类型 sql = ‘select user,pwd from userinfo;‘ cursor.execute(sql) ret1 = cursor.fetchone() # 取一条 ret2 = cursor.fetchmany(3) # 取三条 ret3 = cursor.fetchone() # 取一条 # 可以获取指定数量的数据 cursor.fetchmany(3) # 光标按绝对位置移动1 cursor.scroll(1, mode="absolute") # 光标按照相对位置(当前位置)移动1 cursor.scroll(1, mode="relative") # #数据回滚 # try: # # 拼接并执行SQL语句 # cursor.execute(sql1, [user, pwd]) # cursor.execute(sql2, [id, hobby]) # 报错的SQL语句 # # 涉及写操作注意要提交 # connect.commit() # except Exception as e: # print(str(e)) # # 有异常就回滚 # connect.rollback() # 关闭光标对象 cursor.close() # 关闭数据库连接 connect.close()