连接MySQL有两个模块:mysqldb和pymysql,第一个在Python3.x上不能用,所以我们学pymysql
import pymysql # 创建连接 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, password=‘mysql8‘, db=‘mysqltest‘) # 创建游标(光标) cursor = conn.cursor() # 执行SQL,返回影响行数 effect_rows = cursor.execute("select * from tt") print(effect_rows) # 取前两条 print(cursor.fetchmany(2)) # 取第一条 print(cursor.fetchone()) # 取所有 print(cursor.fetchall()) # 用批量插入语句插入data data = [(7,‘gg‘),(8,‘hh‘),(9,‘ii‘)] cursor.executemany("insert into tt values(%s, %s)", data) conn.commit() cursor.close() conn.close()
原文地址:https://www.cnblogs.com/staff/p/9972080.html
时间: 2024-11-07 16:29:54