python3 链接mysql数据库

1、链接报错

python3 链接数据库 有时候会因为写法不对,而报错

下面的代码是自己在写的时候的总结

import pymysql
#链接数据库需要先导入库
#python3中不支持mysqldb
conn=pymysql.connect(host='数据库地址',user='name',passwd='****',db='blockchain',port=3306,charset='utf8')
#这里要注意port 后要跟随数字,不要写出成port="3306"
#charset 中的utf8 写成“utf-8”会报错
cursor=conn.cursor() #控制光标
cursor.execute(sql语句)
conn.commit()#提交事务
conn.close()# 断开与数据库的链接

关于数据库的操作

2.1查询操作

 1 import pymysql  #导入 pymysql  
 2   
 3 #打开数据库连接  
 4 db= pymysql.connect(host="localhost",user="root",  
 5     password="123456",db="test",port=3307)  
 6   
 7 # 使用cursor()方法获取操作游标  
 8 cur = db.cursor()  
 9   
10 #1.查询操作  
11 # 编写sql 查询语句  user 对应我的表名  
12 sql = "select * from user"  
13 try:  
14     cur.execute(sql)    #执行sql语句  
15   
16     results = cur.fetchall()    #获取查询的所有记录  
17     print("id","name","password")  
18     #遍历结果  
19     for row in results :  
20         id = row[0]  
21         name = row[1]  
22         password = row[2]  
23         print(id,name,password)  
24 except Exception as e:  
25     raise e  
26 finally:  
27     db.close()  #关闭连接  

2.2插入操作

 1 import pymysql  
 2 #2.插入操作  
 3 db= pymysql.connect(host="localhost",user="root",  
 4     password="123456",db="test",port=3307)  
 5   
 6 # 使用cursor()方法获取操作游标  
 7 cur = db.cursor()  
 8   
 9 sql_insert ="""insert into user(id,username,password) values(4,'liu','1234')"""  
10   
11 try:  
12     cur.execute(sql_insert)  
13     #提交  
14     db.commit()  
15 except Exception as e:  
16     #错误回滚  
17     db.rollback()   
18 finally:  
19     db.close()  

2.3更新操作

 1 import pymysql  
 2 #3.更新操作  
 3 db= pymysql.connect(host="localhost",user="root",  
 4     password="123456",db="test",port=3307)  
 5   
 6 # 使用cursor()方法获取操作游标  
 7 cur = db.cursor()  
 8   
 9 sql_update ="update user set username = '%s' where id = %d"  
10   
11 try:  
12     cur.execute(sql_update % ("xiongda",3))  #像sql语句传递参数  
13     #提交  
14     db.commit()  
15 except Exception as e:  
16     #错误回滚  
17     db.rollback()   
18 finally:  
19     db.close()  

2.4删除操作

 1 import pymysql  
 2 #4.删除操作  
 3 db= pymysql.connect(host="localhost",user="root",  
 4     password="123456",db="test",port=3307)  
 5   
 6 # 使用cursor()方法获取操作游标  
 7 cur = db.cursor()  
 8   
 9 sql_delete ="delete from user where id = %d"  
10   
11 try:  
12     cur.execute(sql_delete % (3))  #像sql语句传递参数  
13     #提交  
14     db.commit()  
15 except Exception as e:  
16     #错误回滚  
17     db.rollback()   
18 finally:  
19     db.close() 

参考文章:https://blog.csdn.net/qq_37176126/article/details/72824106

posted @ 2018-06-07 17:09  不负好时光-  阅读(949)  评论(0)    收藏  举报