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

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

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

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

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


上面的代码修改后:

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

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

但若修改为下面:

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\t%s' %row)
    #更新
    cur.execute("update users set name='HAN' where id>2")
    #查询
    cur.execute("select * from users")
    for row in cur.fetchall():
        print('%s\t%s' %row)
    #删除
    cur.execute("delete from users where name='HAN'")
    #查询
    cur.execute("select * from users")
    for row in cur.fetchall():
        print('%s\t%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连接mysql5.7数据库增删改查
参考:http://blog.sina.com.cn/s/blog_154cb570b0102wmyw.html

下面是增删改查功能:

 #!/usr/bin/python3
import pymysql
import types db=pymysql.connect("localhost","root","","python"); cursor=db.cursor() #创建user表
cursor.execute("drop table if exists user")
sql="""CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0""" cursor.execute(sql) #user插入数据
sql="""INSERT INTO `user` (`name`, `age`) VALUES
('test1', 1),
('test2', 2),
('test3', 3),
('test4', 4),
('test5', 5),
('test6', 6);""" try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback() #更新
id=1
sql="update user set age=100 where id='%s'" % (id)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback() #删除
id=2
sql="delete from user where id='%s'" % (id)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback() #查询
cursor.execute("select * from user") results=cursor.fetchall() for row in results:
name=row[0]
age=row[1]
#print(type(row[1])) #打印变量类型 <class 'str'> print ("name=%s,age=%s" % \
(age, name))

下面是我的增删改查:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "blzhu"
"""
python study
Date:2017
"""
import pymysql
import types
try:
# 获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库
conn = pymysql.connect(host='localhost', user='root', passwd='root', db='zbltest1', port=3306, charset='utf8')
cur = conn.cursor() # 获取一个游标
cur.execute("set global max_allowed_packet = 100 * 1024 * 1024 ")
cur.close() # 关闭游标
conn.close() # 释放数据库资源 conn = pymysql.connect(host='localhost', user='root', passwd='root', db='zbltest1', port=3306, charset='utf8')
cur = conn.cursor() # 获取一个游标
cur.execute("DROP table if exists student")
sql = """CREATE TABLE IF NOT EXISTS `student` (
`zid` int(101) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`age` int(101) NOT NULL,
PRIMARY KEY (`zid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"""
cur.execute(sql)
# 增加
for i in range(1, 10):
zbl_id = str(i)
zbl_name = 'zbl'+str(i)
zbl_age = i # 赋值类型一定要正确
# sql = "INSERT student VALUES ('%s','%s','%s')" % (zbl_id, zbl_name, zbl_age) #正确
sql = "INSERT student VALUES ('%s','%s','%d')" % (zbl_id, zbl_name, zbl_age) #'%d'也正确
print(sql)
cur.execute(sql)
conn.commit()# 将数据写入数据库
# 更新
id = 1
sql = "update student set age=100 where zid='%s'" % (id)
try:
cur.execute(sql)
conn.commit()
except:
conn.rollback() # 删除
id = 2
sql = "delete from student where zid='%s'" % (id)
try:
cur.execute(sql)
conn.commit()
except:
conn.rollback()
#查1
cur.execute("select * from user")
results = cur.fetchall()
for row in results:
zid = row[0]
name = row[1]
age = row[2]
# print(type(row[1])) #打印变量类型 <class 'str'> print("zid=%s,name=%s,age=%s" % \
(zid,name, age))
# 查2
cur.execute('select * from student')
for d in cur:
# 注意int类型需要使用str函数转义
print("ID: " + str(d[0]) + ' 名字: ' + d[1] + " 年龄: " + str(d[2]))#当非字符串输出时一定加str()将之转换成字符串
print("row_number:", (cur.rownumber))
# print('hello') cur.close() # 关闭游标
conn.close() # 释放数据库资源
except Exception:
print("发生异常")

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

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

上一篇:Linux TCP拥塞控制算法原理解析


下一篇:深度学习原理与框架-图像补全(原理与代码) 1.tf.nn.moments(求平均值和标准差) 2.tf.control_dependencies(先执行内部操作) 3.tf.cond(判别执行前或后函数) 4.tf.nn.atrous_conv2d 5.tf.nn.conv2d_transpose(反卷积) 7.tf.train.get_checkpoint_state(判断sess是否存在