pip install PyMySQL;
import pymysql
conn = pymysql.connect(host="主机",port=3306,user="用户名",passwd="密码",db="数据库名",charset="utf8")
如果是本机,host填'localhost',port端口号,默认3306,charset字符编码,默认是'gb2312',要求与数据库创建时指定的编码一致,否则中文会乱码
cur = conn.cursor()
# coding = utf-8
import pymysql
con = pymysql.connect(host='localhost',port=3306,user='root',password='123',db='test',charset='utf8') # 创建connect对象
cur = conn.cursor() #创建cursor对象
name = input('请输入添加的学生姓名:')
sql1 = 'insert into students(name) values(%s);'
sql2 = 'delete from students where name = "老王";'
sql3 = 'update students set name = “老张” where name = "老李";'
try:
cur.execute(sql1,[name]) #增加一条数据
cur.execute(sql2) #删除一条数据
cur.execute(sql3) #修改一条数据
except Exception as e:
print(e)
con.rollback() # 放弃之前的所有操作
else:
con.commit() # 提交,使所有操作生效
cur.close() # 关闭cursor对象
con.close() # 关闭连接
# coding = utf-8
import pymysql
con = pymysql.connect(host='localhost',port=3306,user='root',password='123',db='test',charset='utf8') # 创建connect对象
cur = conn.cursor() #创建cursor对象
try:
sql = 'select * from students;'
count = cur.execute(sql)
data1 = cur.fetchone() #查找第一行数据
print(data1)
data2 = cur.fetchall() # 查找剩下所有行数据
print(data2)
except Exception as e:
print(e)
cur.close()
con.close()
手机扫一扫
移动阅读更方便
你可能感兴趣的文章