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生成指定长度的随机数密码
Jan 23 Python
python类继承用法实例分析
Oct 10 Python
深入讲解Java编程中类的生命周期
Feb 05 Python
Python实现TCP/IP协议下的端口转发及重定向示例
Jun 14 Python
Python 数据可视化pyecharts的使用详解
Jun 26 Python
如何通过python的fabric包完成代码上传部署
Jul 29 Python
基于python判断目录或者文件代码实例
Nov 29 Python
opencv3/C++实现视频读取、视频写入
Dec 11 Python
python 通过邮件控制实现远程控制电脑操作
Mar 16 Python
python使用hdfs3模块对hdfs进行操作详解
Jun 06 Python
Keras之fit_generator与train_on_batch用法
Jun 17 Python
PyQt5结合matplotlib绘图的实现示例
Sep 15 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
浅谈PHP语法(1)
2006/10/09 PHP
php创建基本身份认证站点的方法详解
2013/06/08 PHP
Laravel自动生成UUID,从建表到使用详解
2019/10/24 PHP
PHP字符串与数组处理函数用法小结
2020/01/07 PHP
Mootools 1.2教程 同时进行多个形变动画
2009/09/15 Javascript
javascript下利用arguments实现string.format函数
2010/08/24 Javascript
jQuery-ui引入后Vs2008的无智能提示问题解决方法
2014/02/10 Javascript
js常用数组操作方法简明总结
2014/06/20 Javascript
JQuery.get提交页面不跳转的解决方法
2015/01/13 Javascript
jQuery Ajax中的事件详细介绍
2015/04/16 Javascript
JS实现的页面自定义滚动条效果
2015/10/26 Javascript
JavaScript数据结构与算法之集合(Set)
2016/01/29 Javascript
详细AngularJs4的图片剪裁组件的实例
2017/07/12 Javascript
jQuery响应滚动条事件功能示例
2017/10/14 jQuery
SpringBoot+Vue前后端分离,使用SpringSecurity完美处理权限问题的解决方法
2018/01/09 Javascript
微信实现自动跳转到用其他浏览器打开指定APP下载
2019/02/15 Javascript
[02:32]【DOTA2亚洲邀请赛】iceice,梦开始的地方
2017/03/13 DOTA
python遍历序列enumerate函数浅析
2017/10/17 Python
python3中函数参数的四种简单用法
2018/07/09 Python
用python写一个定时提醒程序的实现代码
2019/07/22 Python
Python 单例设计模式用法实例分析
2019/09/23 Python
Python读取配置文件(config.ini)以及写入配置文件
2020/04/08 Python
一文弄懂Pytorch的DataLoader, DataSet, Sampler之间的关系
2020/07/03 Python
Python如何绘制日历图和热力图
2020/08/07 Python
python3.9.1环境安装的方法(图文)
2021/02/02 Python
使用CSS Grid布局实现网格的流动
2014/12/30 HTML / CSS
详解CSS3选择器:nth-child和:nth-of-type之间的差异
2017/09/18 HTML / CSS
Jacadi Paris美国官方网站:法国童装品牌
2017/10/15 全球购物
介绍下static、final、abstract区别
2015/01/30 面试题
市级优秀班主任事迹材料
2014/05/13 职场文书
危货运输企业安全生产责任书
2014/07/28 职场文书
北京颐和园导游词
2015/01/30 职场文书
全陪导游词
2015/02/04 职场文书
催款通知书范文
2015/04/17 职场文书
小组组名及励志口号
2015/12/24 职场文书
python如何进行基准测试
2021/04/26 Python