python安装pymysql模块
实例一:
import pymysql
#建立数据库连接
db=pymysql.connect(host='192.168.59.128',user='root1',passwd='123456',db='test',port=3306)
#使用cursor()方法获取操作游标
cursor=db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("select version()")
# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
print("Database version : %s " % data)
# 关闭数据库连接
db.close()
结果:Database version : 5.6.16
对数据查询操作
import pymysql
db=pymysql.connect(host='192.168.59.128',user='root1',passwd='123456',db='test',charset='utf8')
cursor=db.cursor()
sql="select * from students"
try:
cursor.execute(sql)
#获取全部的数据
results=cursor.fetchall()
print(results)
#遍历结果集
for row in results:
id=row[0]
name=row[1]
sex=row[2]
age=row[3]
classes=row[4]
addr=row[5]
print(id,name,sex,age,classes,addr)
except:
print("can not find the table")
db.close()
增删改操作
import pymysql
db=pymysql.connect("192.168.59.128",'root1','123456','test',charset="utf8")
cursor=db.cursor()
#sql="insert into students VALUES (1009,'张飞','男',30,'白胡子','上海')"
#sql="update students set name='皇马' where id=801"
sql="delete from students where id=1009"
try:
cursor.execute(sql)
#数据发生改动需要commit
db.commit()
except:
#如果执行不成功数据回滚
db.rollback()
db.close()