标签:数据库更新 mysql date 读取 res 执行 更新 abs tuple
1 pip3 install pymysql
2.1.执行原生sql语句
1 import pymysql 2 conn = pymysql.connect(host=‘192.168.48.20‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘test‘) # 创建连接 3 cursor = conn.cursor() # 创建游标 4 # num = cursor.execute("create table student (name CHAR(20),age INT(3),date DATE )") # 创建表不需要提交可以生效 5 num = cursor.execute("insert into student value(‘hua‘,25,‘1992-05-22‘)") # 执行sql返回受影响的条目数 6 print(num) 7 conn.commit() # pymysql默认开启了事务,进行数据库更新需要提交 8 cursor.close() # 关闭游标 9 conn.close() # 关闭连接
1 import pymysql 2 conn = pymysql.connect(host=‘192.168.48.20‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘test‘) # 创建连接 3 cursor = conn.cursor() # 创建游标 4 # 一次性执行操作多条,参数为print(num)#打印条结果条目 5 num = cursor.executemany("insert into student values(%s,%s,%s)", [(‘jack‘, 22, ‘1993-01-11‘), (‘tara‘, 18, ‘1998-03-04‘)]) 6 conn.commit() # pymysql默认开启了事务,进行数据库更新需要提交 7 new_id = cursor.lastrowid # 如果是自增id,该方法可以获取到插入完成以后的IDprint(new_id) 8 cursor.close() # 关闭游标 9 conn.close() # 关闭连接
2.3.查询操作:fetch
1 import pymysql 2 conn = pymysql.connect(host=‘192.168.48.20‘, port=3306, user=‘root‘, passwd=‘123‘, db=‘test‘) # 创建连接 3 cursor = conn.cursor() # 创建游标 4 cursor = conn.cursor() 5 cursor.execute("select * from student") 6 # 获取第一行数据 7 row_1 = cursor.fetchone() 8 print(row_1) 9 # 获取前n行数据 10 row_2 = cursor.fetchmany(3) 11 print(row_2) 12 # 获取所有数据 13 # row_3=cursor.fetchall() 14 cursor.scroll(0, mode=‘absolute‘) # 将游标重新移至开始处 15 row_new = cursor.fetchone() 16 print(row_new) 17 cursor.close() # 关闭游标 18 conn.close() # 关闭连接
可以使用cursor.scroll(num,mode)来移动游标位置,如:
1 import pymysql 2 3 conn = pymysql.connect(host=‘192.168.48.20‘,port=3306,user=‘root‘,passwd=‘123‘,db=‘test‘) 4 # 游标设置为字典类型 5 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 设置游标类型为字典 6 r = cursor.execute("select * from student") 7 res = cursor.fetchone() 8 print(res) 9 cursor.close() 10 conn.close() 11 结果: 12 {‘name‘: ‘bg‘, ‘age‘: 22, ‘date‘: datetime.date(1993, 5, 22)}
标签:数据库更新 mysql date 读取 res 执行 更新 abs tuple
原文地址:http://www.cnblogs.com/breakering/p/7076287.html