python3.4连接mysql5.7数据库增删改查

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __author__ = "blzhu"
 4 """
 5 python study
 6 Date:2017
 7 """
 8 import pymysql
 9 import types
10 try:
11     # 获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库
12     conn = pymysql.connect(host='localhost', user='root', passwd='root', db='zbltest1', port=3306, charset='utf8')
13     cur = conn.cursor()  # 获取一个游标
14     cur.execute("DROP table if exists student")
15     sql = """CREATE TABLE IF NOT EXISTS `student` (
16           `zid` int(11) NOT NULL ,
17           `name` varchar(255) NOT NULL,
18           `age` int(11) NOT NULL,
19           PRIMARY KEY (`zid`)
20         ) ENGINE=InnoDB  DEFAULT CHARSET=utf8"""
21     cur.execute(sql)
22     for i in range(1, 100):
23         zbl_id = str(i)
24         zbl_name = 'zbl'+str(i)
25         zbl_age = i # 赋值类型一定要正确
26         sql = "INSERT student VALUES ('%s','%s','%s')" % (zbl_id, zbl_name, zbl_age)
27         print(sql)
28         cur.execute(sql)
29     conn.commit()# 将数据写入数据库
30 
31     cur.execute('select * from student')
32     # data=cur.fetchall()
33     for d in cur:
34         # 注意int类型需要使用str函数转义
35         print("ID: " + str(d[0]) + '  名字: ' + d[1] + "  年龄: " + str(d[2]))#当非字符串输出时一定加str()将之转换成字符串
36     print("row_number:", (cur.rownumber))
37     # print('hello')
38 
39     cur.close()  # 关闭游标
40     conn.close()  # 释放数据库资源
41 except  Exception:
42     print("发生异常")

记得每次运算后在mysql workbench中要刷新才能体现出来有没有新增表格。


上面的代码修改后:

1     sql = """CREATE TABLE IF NOT EXISTS `student` (
2           `zid` int(11) NOT NULL AUTO_INCREMENT,
3           `name` varchar(255) NOT NULL,
4           `age` int(11) NOT NULL,
5           PRIMARY KEY (`zid`)
6         ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2"""

运行结果仍然一样,可以理解为自动增加的优先级不如手动增加的优先级。

但若修改为下面:

 1 sql = "INSERT into 'student' VALUES ('%s','%s','%s')" % (zbl_id, zbl_name, zbl_age) 

就会发生错误,错在student不应该加引号。into加不加都行。

sql = "INSERT into 'student' ('zid','name','age') VALUES ('%s','%s','%s')" % (zbl_id, zbl_name, zbl_age)
也会发生错误。

1.DB-API

应用程序编程接口(API)是访问某些服务的函数集合,DB-API是python中访问关系型数据库的API,它定义了一系列必要的对象和数据库获取方式,以便为各种各样的底层数据库系统和各种各样的数据库程序提供一致的访问接口。
Python DB-API的使用流程:
引入API模块
获取与数据库的连接
执行SQl语句和存储过程
关闭数据库连接
DB-API的主要函数:
connect():连接数据库,包含参数用户名、密码、服务器地址等等
cursor():创建一个cursor对象来管理下查询
execute()和executemany():对数据库执行一个或者多个SQL命令
fetchone()、fetchmany()和fetchall():得到execute之后的结果
2.Python3.4连接MySQL的环境搭建(参考)
http://blog.csdn.net/yannanxiu/article/details/50486887
3.python操作MySQl简单实例:
import mysql.connector
#打开数据库连接
db=mysql.connector.connect(user='root',password='root',host='localhost',database='words')
#使用cursor()方法创建一个cursor对象,来管理查询
cur=db.cursor()
#使用execute()方法执行SQL,如果存在则删除
cur.execute("drop table if exists users")
#使用预处理创建表
cur.execute(" create table users (id INT,name varchar(8))")
try:
    #插入数据
    cur.execute("insert into users values(1,'www'),(2,'sss'),(3,'ccc'),(4,'tsgs')")
    #查询
    cur.execute("select * from users")
    for row in cur.fetchall():
        print('%s %s' %row)
    #更新
    cur.execute("update users set name='HAN' where id>2")
    #查询
    cur.execute("select * from users")
    for row in cur.fetchall():
        print('%s %s' %row)
    #删除
    cur.execute("delete from users where name='HAN'")
    #查询
    cur.execute("select * from users")
    for row in cur.fetchall():
        print('%s %s' %row)
except:
    #发生错误时回滚
    db.rollback()
    print("Error,。。。。")
#关闭
db.close()
结果:
1 www
2 sss
3 ccc
4 tsgs
 
1 www
2 sss
3 HAN
4 HAN
 
1 www
2 sss
 
4.错误处理
DB-API中定义了一些数据库操作的错误及异常
python3.4 <wbr>MySQL的简单使用
参考:http://blog.sina.com.cn/s/blog_154cb570b0102wmyw.html

下面是增删改查功能:

 1 #!/usr/bin/python3  
 2 import pymysql  
 3 import types  
 4   
 5 db=pymysql.connect("localhost","root","123456","python");  
 6   
 7 cursor=db.cursor()  
 8   
 9 #创建user表  
10 cursor.execute("drop table if exists user")  
11 sql="""CREATE TABLE IF NOT EXISTS `user` ( 
12       `id` int(11) NOT NULL AUTO_INCREMENT, 
13       `name` varchar(255) NOT NULL, 
14       `age` int(11) NOT NULL, 
15       PRIMARY KEY (`id`) 
16     ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"""  
17   
18 cursor.execute(sql)  
19   
20   
21 #user插入数据  
22 sql="""INSERT INTO `user` (`name`, `age`) VALUES 
23 ('test1', 1), 
24 ('test2', 2), 
25 ('test3', 3), 
26 ('test4', 4), 
27 ('test5', 5), 
28 ('test6', 6);"""  
29   
30 try:  
31    # 执行sql语句  
32    cursor.execute(sql)  
33    # 提交到数据库执行  
34    db.commit()  
35 except:  
36    # 如果发生错误则回滚  
37    db.rollback()  
38      
39      
40 #更新  
41 id=1  
42 sql="update user set age=100 where id='%s'" % (id)  
43 try:  
44     cursor.execute(sql)  
45     db.commit()  
46 except:  
47     db.rollback()  
48       
49 #删除  
50 id=2  
51 sql="delete from user where id='%s'" % (id)  
52 try:  
53     cursor.execute(sql)  
54     db.commit()  
55 except:  
56     db.rollback()  
57       
58       
59 #查询  
60 cursor.execute("select * from user")  
61   
62 results=cursor.fetchall()  
63   
64 for row in results:  
65     name=row[0]  
66     age=row[1]  
67     #print(type(row[1])) #打印变量类型 <class 'str'>  
68   
69     print ("name=%s,age=%s" %   
70              (age, name)) 
View Code

下面是我的增删改查:

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __author__ = "blzhu"
 4 """
 5 python study
 6 Date:2017
 7 """
 8 import pymysql
 9 import types
10 try:
11     # 获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库
12     conn = pymysql.connect(host='localhost', user='root', passwd='root', db='zbltest1', port=3306, charset='utf8')
13     cur = conn.cursor()  # 获取一个游标
14     cur.execute("set global max_allowed_packet = 100 * 1024 * 1024 ")
15     cur.close()  # 关闭游标
16     conn.close()  # 释放数据库资源
17 
18     conn = pymysql.connect(host='localhost', user='root', passwd='root', db='zbltest1', port=3306, charset='utf8')
19     cur = conn.cursor()  # 获取一个游标
20     cur.execute("DROP table if exists student")
21     sql = """CREATE TABLE IF NOT EXISTS `student` (
22           `zid` int(101) NOT NULL AUTO_INCREMENT,
23           `name` varchar(255) NOT NULL,
24           `age` int(101) NOT NULL,
25           PRIMARY KEY (`zid`)
26         ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"""
27     cur.execute(sql)
28     # 增加
29     for i in range(1, 10):
30         zbl_id = str(i)
31         zbl_name = 'zbl'+str(i)
32         zbl_age = i # 赋值类型一定要正确
33         # sql = "INSERT  student VALUES ('%s','%s','%s')" % (zbl_id, zbl_name, zbl_age) #正确
34         sql = "INSERT  student  VALUES ('%s','%s','%d')" % (zbl_id, zbl_name, zbl_age) #'%d'也正确
35         print(sql)
36         cur.execute(sql)
37     conn.commit()# 将数据写入数据库
38     # 更新
39     id = 1
40     sql = "update student set age=100 where zid='%s'" % (id)
41     try:
42         cur.execute(sql)
43         conn.commit()
44     except:
45         conn.rollback()
46 
47         #  删除
48     id = 2
49     sql = "delete from student where zid='%s'" % (id)
50     try:
51         cur.execute(sql)
52         conn.commit()
53     except:
54         conn.rollback()
55     #查1
56     cur.execute("select * from user")
57     results = cur.fetchall()
58     for row in results:
59         zid = row[0]
60         name = row[1]
61         age = row[2]
62         # print(type(row[1])) #打印变量类型 <class 'str'>
63 
64         print("zid=%s,name=%s,age=%s" % 
65               (zid,name, age))
66     # 查2
67     cur.execute('select * from student')
68     for d in cur:
69         # 注意int类型需要使用str函数转义
70         print("ID: " + str(d[0]) + '  名字: ' + d[1] + "  年龄: " + str(d[2]))#当非字符串输出时一定加str()将之转换成字符串
71     print("row_number:", (cur.rownumber))
72     # print('hello')
73 
74     cur.close()  # 关闭游标
75     conn.close()  # 释放数据库资源
76 except  Exception:
77     print("发生异常")

原文地址:https://www.cnblogs.com/zhubinglong/p/7053220.html