python3 连接数据库注意点

类库:pymysql

 1 '''
 2 Created on 2019年
 3 
 4 @author: Root
 5 '''
 6 import pymysql
 7 from name import getName
 8 # 数据库连接信息
 9 conn = pymysql.connect('localhost','root','root','myown',charset='utf8')
10 # 错误写法: utf-8   UTF-8
11 # 正确写法:utf8   UTF8
12 # 创建游标
13 cursor = conn.cursor()
14 
15 class DBUtils:
16     
17     # 新增数据
18     def add(self):
19         try:
20             name = getName()
21             sql = 'insert into test(name) values(%s)'
22             cursor.execute(sql,name)
23             conn.commit()
24             print ('新增数据成功')
25         except:
26             conn.callback()
27             print ('新增出错,事务回滚')
28    
29     # 查询数据
30     def query(self):
31 #         sql = "select * from test1"
32         sql = "select count(1) from test"
33         cursor.execute(sql)
34 #         result = cursor.fetchone()
35         result = cursor.fetchall()
36         print (result)
37      
38     # 删除数据
39     def delDate(self):
40         sql = "delete from test1 where id = '%s';"
41         try:
42             cursor.execute(sql,2)
43             conn.commit()
44             print ('删除成功')
45         except:
46             conn.callback()
47             print ('删除失败')
48     # 修改数据      
49     def update(self):
50         sql = 'update test1 set name = %s where id = %s;'
51         try:
52             cursor.execute(sql,('赵四',4))
53             conn.commit()
54             print ('数据更新成功')
55         except Exception as e:
56             print (e.getMessage())
57             conn.callback()
58             print ('数据更新失败')
59     
60 # for i in range(100000):
61 #     DBUtils().add()
62 
63 DBUtils().query()
64 # DBUtils().delDate()
65 # DBUtils().update()
66 
67 conn.close()
View Code

注意点:

数据库连接信息写法

1.     host='localhost',port=3306,user='root',passwd='root',db='myown',charset='utf8'
2.     host='localhost',port=3306,user='root',password='root',db='myown',charset='utf8'
3.     'localhost','root','root','myown',charset='utf8'

编码格式必须为:  utf8或者UTF8

转载于:https://www.cnblogs.com/wdzy/p/11177921.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值