python3.4用循环往mysql5.7中写数据并输出的实现方法


Posted in Python onJune 20, 2017

如下所示:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "blzhu"
"""
python study
Date:2017
"""
import pymysql
# import MySQLdb #python2中的产物

try:
  # 获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库
  conn = pymysql.connect(host='localhost', user='root', passwd='root', db='zbltest1', port=3306, charset='utf8')
  cur = conn.cursor() # 获取一个游标
  for i in range(1, 10):
    zbl_id = str(i)
    zbl_name = 'zbl'+str(i)
    zbl_gender = 'man'
    # print("%s,%s,%s" % (zbl_id,zbl_name,zbl_gender))
    # sql = "insert student VALUES (id='%s',name='%s',gender='%s')" % (zbl_id,zbl_name,zbl_gender)
    sql = "insert student VALUES ('%s','%s','%s')" % (zbl_id, zbl_name, zbl_gender)
    # print(sql)
    cur.execute(sql)
  conn.commit()# 将数据写入数据库

    # try:
    # cur.execute(sql)
      # cur.commit()
    # except:
    #   cur.rollback()
    #cur.execute("""INSERT INTO 'student' ('id','name','gender') VALUES (%s,%s,%s ,(zbl_id,zbl_name,zbl_gender,))""")
    #cur.execute("""INSERT INTO 'student' ('id','name','gender') VALUES (zbl_id,zbl_name,zbl_gender)""")

    # cur.execute("INSERT student VALUES (zbl_id,zbl_name,zbl_gender)")

  # cur.execute("INSERT student VALUES ('4', 'zbl4', 'man')")# 正确
  #cur.execute("INSERT INTO 'student' ('id','name','gender') VALUES ('4', 'zbl4', 'man')")#错误
  #cur.execute("INSERT student ('id','name','gender') VALUES ('4', 'zbl4', 'man')")


  cur.execute('select * from student')
  # data=cur.fetchall()
  for d in cur:
    # 注意int类型需要使用str函数转义
    print("ID: " + str(d[0]) + ' 名字: ' + d[1] + " 性别: " + d[2])
  print("row_number:", (cur.rownumber))
  # print('hello')

  cur.close() # 关闭游标
  conn.close() # 释放数据库资源
except Exception:
  print("发生异常")

上面代码是对的,但是是曲折的。

下面整理一下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "blzhu"
"""
python study
Date:2017
"""
import pymysql
try:
  # 获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库
  conn = pymysql.connect(host='localhost', user='root', passwd='root', db='zbltest1', port=3306, charset='utf8')
  cur = conn.cursor() # 获取一个游标
  for i in range(1, 10):
    zbl_id = str(i)
    zbl_name = 'zbl'+str(i)
    zbl_gender = 'man'
    # print("%s,%s,%s" % (zbl_id,zbl_name,zbl_gender))
    # sql = "insert student VALUES (id='%s',name='%s',gender='%s')" % (zbl_id,zbl_name,zbl_gender)
    sql = "insert student VALUES ('%s','%s','%s')" % (zbl_id, zbl_name, zbl_gender)
    # 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] + " 性别: " + d[2])
  print("row_number:", (cur.rownumber))
  # print('hello')

  cur.close() # 关闭游标
  conn.close() # 释放数据库资源
except Exception:
  print("发生异常")
#!/usr/bin/python3
import pymysql
import types

db=pymysql.connect("localhost","root","123456","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))

以上这篇python3.4用循环往mysql5.7中写数据并输出的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
从零学Python之入门(四)运算
May 27 Python
python采用requests库模拟登录和抓取数据的简单示例
Jul 05 Python
python中sys.argv参数用法实例分析
May 20 Python
在Python中操作时间之mktime()方法的使用教程
May 22 Python
详解Python的collections模块中的deque双端队列结构
Jul 07 Python
python reduce 函数使用详解
Dec 05 Python
python针对excel的操作技巧
Mar 13 Python
matplotlib实现热成像图colorbar和极坐标图的方法
Dec 13 Python
django url到views参数传递的实例
Jul 19 Python
Python 中 -m 的典型用法、原理解析与发展演变
Nov 11 Python
Pandas的Apply函数具体使用
Jul 21 Python
python基础详解之if循环语句
Apr 24 Python
Python实现多并发访问网站功能示例
Jun 19 #Python
Python sqlite3事务处理方法实例分析
Jun 19 #Python
Python之str操作方法(详解)
Jun 19 #Python
python urllib爬取百度云连接的实例代码
Jun 19 #Python
Python的IDEL增加清屏功能实例
Jun 19 #Python
利用python爬取散文网的文章实例教程
Jun 18 #Python
Python3中简单的文件操作及两个简单小实例分享
Jun 18 #Python
You might like
ionCube 一款类似zend的PHP加密/解密工具
2010/07/25 PHP
需要注意的几个PHP漏洞小结
2012/02/05 PHP
WordPress自定义时间显示格式
2015/03/27 PHP
PHP+Mysql+jQuery实现发布微博程序 php篇
2015/10/15 PHP
PHP搭建大文件切割分块上传功能示例
2017/01/04 PHP
页面中body onload 和 window.onload 冲突的问题的解决
2009/07/01 Javascript
扩展jQuery 键盘事件的几个基本方法
2009/10/30 Javascript
js+xml生成级联下拉框代码
2012/07/24 Javascript
jquery加载图片时以淡入方式显示的方法
2015/01/14 Javascript
jQuery 回调函数(callback)的使用和基础
2015/02/26 Javascript
一张Web前端的思维导图分享
2015/07/03 Javascript
Javascript实现鼠标右键特色菜单
2015/08/04 Javascript
javascript实现dom元素可拖动
2016/03/21 Javascript
老生常谈JavaScript 函数表达式
2016/09/01 Javascript
JS只能输入正整数的简单实例
2016/10/07 Javascript
浅析script标签中的defer与async属性
2016/11/30 Javascript
Angular 4.x 动态创建表单实例
2017/04/25 Javascript
详解Angular Reactive Form 表单验证
2017/07/06 Javascript
JS与CSS3实现图片响应鼠标移动放大效果示例
2018/05/04 Javascript
[01:30]DOTA2上海特锦赛现场采访 Loda倾情献唱
2016/03/25 DOTA
python列表与元组详解实例
2013/11/01 Python
python基于xml parse实现解析cdatasection数据
2014/09/30 Python
python之pandas用法大全
2018/03/13 Python
Python寻找路径和查找文件路径的示例
2019/07/10 Python
TensorFlow通过文件名/文件夹名获取标签,并加入队列的实现
2020/02/17 Python
Keras框架中的epoch、bacth、batch size、iteration使用介绍
2020/06/10 Python
HTML5画渐变背景图片并自动下载实现步骤
2013/11/18 HTML / CSS
HTML 5 input placeholder 属性如何完美兼任ie
2014/05/12 HTML / CSS
李维斯牛仔裤英国官方网站:Levi’s英国
2019/10/10 全球购物
为什么要优先使用同步代码块而不是同步方法?
2013/01/30 面试题
购房协议书
2014/04/11 职场文书
三好学生评语大全
2014/12/29 职场文书
2015年底工作总结范文
2015/05/15 职场文书
红色故事汇观后感
2015/06/18 职场文书
2016年春季趣味运动会开幕词
2016/03/04 职场文书
七年级之家长会发言稿范文
2019/09/04 职场文书