首页 > 数据库技术 > 详细

python3 连接数据库注意点

时间:2019-07-12 19:49:24      阅读:90      评论:0      收藏:0      [点我收藏+]

类库: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

python3 连接数据库注意点

原文:https://www.cnblogs.com/wdzy/p/11177921.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!