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("发生异常")
记得每次运算后在mysql workbench中要刷新才能体现出来有没有新增表格。
上面的代码修改后:
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
下面是增删改查功能:
#!/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数据库增删改查的更多相关文章
- Java连接MySQL数据库增删改查通用方法
版权声明:本文为博主原创文章,未经博主允许不得转载. Java连接MySQL数据库增删改查通用方法 运行环境:eclipse+MySQL 以前我们Java连接MySQL数据库都是一个数据库写一个类,类 ...
- Asp.Net操作MySql数据库增删改查
Asp.Net操作MySql数据库增删改查,话不多说直接步入正题.git源码地址:https://git.oschina.net/gxiaopan/NetMySql.git 1.安装MySQL数据库 ...
- go——beego的数据库增删改查
一直都不理解使用go语言的时候,为什么还要自己去装beego,以为使用go便可以解决所有的问题,结果在朋友的点拨下,才意识到: go与beego的关系就好比是nodejs与thinkjs的关系,因此也 ...
- WindowsPhone8 数据库增删改查
今天第一次在博客园发表文章,如果有的地方写的不对,还请大家指出! 1.这就是一个简单wp8数据库增删改查 1.创建数据表Person [Table] public class Person : INo ...
- MVC——数据库增删改查(aspx)
MVC: V(View) :视图→就是页面的模板 C(Control): 控制器→客户主要面对的就是控制器, M(Model):模板→在模板里面主要就是写关于数据库的各种增删改查的方法 它们之间的关系 ...
- python操作mysql数据库增删改查的dbutils实例
python操作mysql数据库增删改查的dbutils实例 # 数据库配置文件 # cat gconf.py #encoding=utf-8 import json # json里面的字典不能用单引 ...
- mybatis--实现数据库增删改查
首先,创建一个数据库my,并在数据库中插入一张表user,然后在user表中插入一行数据,代码如下: create database my; use my; create table user( id ...
- Python实现mysql数据库增删改查
利用python操作mysql数据库用法简单,环境配置容易,本文将实现对库增.删.改.查的简易封装! 1. 环境配置 安装第三方包 ,导入模块 mysql.connector pip inst ...
- NX二次开发-NX访问SqlServer数据库(增删改查)C#版
版本:NX9+VS2012+SqlServer2008r2 以前我写过一个NX访问MySQL数据库(增删改查)的文章https://www.cnblogs.com/nxopen2018/p/12297 ...
随机推荐
- Springboot学习02-webjars和静态资源映射规则
Springboot学习01-webjars和静态资源映射规则 前言 1-以前我们在IDEA中创建一个项目,添加web依赖包,我们现在是一个web应用,应该在man目录下面有一个webapp文件夹,将 ...
- JQuery|jstl判断是否为空
//有如下三种判断 var A=$("#**).val(); if(A==null||A==undefined||A==""){ //处理 } //参考文章1说下面方法效 ...
- ios 错误纪录
.self.出不来的原因 Member reference type 'struct objc_class *' is a pointer; maybe you meant to use '-> ...
- Repeater控件添加序号列
在项目开发过程中,会经常遇到ASP.NET repeater控件添加序号列,有些新手可能还不会,网上搜集整理了一些,需要的朋友可以参考下 ASP.NET repeater添加序号列的方法 1.< ...
- openshift上传java web项目
下载当前客户端 OC(Openshift Client) https://mirror.openshift.com/pub/openshift-v3/clients/3.9.14/windows/oc ...
- 序列化、模块 day21
一 序列化 什么叫序列化——将原本的字典.列表等内容转换成一个字符串的过程就叫做序列化. 字典示例 import json d={'a':1,'b':2} ret = json.dumps(d)# ...
- Sublime Text3 常用快捷键必看
Sublime Text3 常用快捷键必看 https://blog.csdn.net/md1688/article/details/53043525
- Python中的 __all__和__path__ 解析
https://blog.csdn.net/u012450329/article/details/53001071
- git 分支的创建和切换
每次提交,GIT 都会将他们串成一个时间线,截止到目前,只有一个时间线,GIT里叫这个分支为主分支,叫master,HEAD指向master,master指向提交,HEAD指向当前的分支. 一开始的时 ...
- Linux CentOS 7 & JDK 1.7 安装与配置
前言 简单记录一下在CentOS 7中安装配置JDK 1.7的全过程~ 下载 首先是jdk 1.7 64bit & 32bit的下载地址: jdk-7u79-linux-x64.tar.gz ...