#!/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

应用程序编程接口(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中定义了一些数据库操作的错误及异常
参考: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数据库增删改查的更多相关文章

  1. Java连接MySQL数据库增删改查通用方法

    版权声明:本文为博主原创文章,未经博主允许不得转载. Java连接MySQL数据库增删改查通用方法 运行环境:eclipse+MySQL 以前我们Java连接MySQL数据库都是一个数据库写一个类,类 ...

  2. Asp.Net操作MySql数据库增删改查

    Asp.Net操作MySql数据库增删改查,话不多说直接步入正题.git源码地址:https://git.oschina.net/gxiaopan/NetMySql.git  1.安装MySQL数据库 ...

  3. go——beego的数据库增删改查

    一直都不理解使用go语言的时候,为什么还要自己去装beego,以为使用go便可以解决所有的问题,结果在朋友的点拨下,才意识到: go与beego的关系就好比是nodejs与thinkjs的关系,因此也 ...

  4. WindowsPhone8 数据库增删改查

    今天第一次在博客园发表文章,如果有的地方写的不对,还请大家指出! 1.这就是一个简单wp8数据库增删改查 1.创建数据表Person [Table] public class Person : INo ...

  5. MVC——数据库增删改查(aspx)

    MVC: V(View) :视图→就是页面的模板 C(Control): 控制器→客户主要面对的就是控制器, M(Model):模板→在模板里面主要就是写关于数据库的各种增删改查的方法 它们之间的关系 ...

  6. python操作mysql数据库增删改查的dbutils实例

    python操作mysql数据库增删改查的dbutils实例 # 数据库配置文件 # cat gconf.py #encoding=utf-8 import json # json里面的字典不能用单引 ...

  7. mybatis--实现数据库增删改查

    首先,创建一个数据库my,并在数据库中插入一张表user,然后在user表中插入一行数据,代码如下: create database my; use my; create table user( id ...

  8. Python实现mysql数据库增删改查

    利用python操作mysql数据库用法简单,环境配置容易,本文将实现对库增.删.改.查的简易封装!   1. 环境配置 安装第三方包  ,导入模块 mysql.connector  pip inst ...

  9. NX二次开发-NX访问SqlServer数据库(增删改查)C#版

    版本:NX9+VS2012+SqlServer2008r2 以前我写过一个NX访问MySQL数据库(增删改查)的文章https://www.cnblogs.com/nxopen2018/p/12297 ...

随机推荐

  1. Springboot学习02-webjars和静态资源映射规则

    Springboot学习01-webjars和静态资源映射规则 前言 1-以前我们在IDEA中创建一个项目,添加web依赖包,我们现在是一个web应用,应该在man目录下面有一个webapp文件夹,将 ...

  2. JQuery|jstl判断是否为空

    //有如下三种判断 var A=$("#**).val(); if(A==null||A==undefined||A==""){ //处理 } //参考文章1说下面方法效 ...

  3. ios 错误纪录

    .self.出不来的原因 Member reference type 'struct objc_class *' is a pointer; maybe you meant to use '-> ...

  4. Repeater控件添加序号列

    在项目开发过程中,会经常遇到ASP.NET repeater控件添加序号列,有些新手可能还不会,网上搜集整理了一些,需要的朋友可以参考下 ASP.NET repeater添加序号列的方法 1.< ...

  5. openshift上传java web项目

    下载当前客户端 OC(Openshift Client) https://mirror.openshift.com/pub/openshift-v3/clients/3.9.14/windows/oc ...

  6. 序列化、模块 day21

      一 序列化 什么叫序列化——将原本的字典.列表等内容转换成一个字符串的过程就叫做序列化. 字典示例 import json d={'a':1,'b':2} ret = json.dumps(d)# ...

  7. Sublime Text3 常用快捷键必看

    Sublime Text3 常用快捷键必看  https://blog.csdn.net/md1688/article/details/53043525

  8. Python中的 __all__和__path__ 解析

    https://blog.csdn.net/u012450329/article/details/53001071

  9. git 分支的创建和切换

    每次提交,GIT 都会将他们串成一个时间线,截止到目前,只有一个时间线,GIT里叫这个分支为主分支,叫master,HEAD指向master,master指向提交,HEAD指向当前的分支. 一开始的时 ...

  10. Linux CentOS 7 & JDK 1.7 安装与配置

    前言 简单记录一下在CentOS 7中安装配置JDK 1.7的全过程~ 下载 首先是jdk 1.7 64bit & 32bit的下载地址: jdk-7u79-linux-x64.tar.gz ...