python(pymysql操作数据库)
第一种方式
import pymysql
# 打开数据库连接
db = pymysql.connect(host="192.168.88.11", user="root",
password="123", db="p1807", port=3306)
# 使用cursor()方法获取操作游标
cur = db.cursor()
# 1.查询操作
# 编写sql 查询语句 user 对应我的表名
sql = "select * from students"
try:
cur.execute(sql) # 执行sql语句
results = cur.fetchall() # 获取查询的所有记录
for i in results:#遍历结果
print(i)
except Exception as e:
raise e
finally:
db.close() # 关闭连接
第二种方式
# 打开数据库连接
db = pymysql.connect(host="192.168.88.11", user="root",
password="123", db="aaa", port=3306)
cur = db.cursor()
try:
for i in range(1000):
cur.execute("insert into qqq values ('ccc-%s')'` %i)
results = cur.fetchall() # 获取查询的所有记录
db.commit() #提交
except Exception as e:
raise e
finally:
db.close() # 关闭连接