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 getopt 参数处理小示例
Jun 09 Python
Python代理抓取并验证使用多线程实现
May 03 Python
python使用pil生成缩略图的方法
Mar 26 Python
python使用cStringIO实现临时内存文件访问的方法
Mar 26 Python
Python中使用第三方库xlutils来追加写入Excel文件示例
Apr 05 Python
详解详解Python中writelines()方法的使用
May 25 Python
python中判断文件编码的chardet(实例讲解)
Dec 21 Python
pygame实现雷电游戏雏形开发
Nov 20 Python
Python+OpenCV感兴趣区域ROI提取方法
Jan 10 Python
python3 中使用urllib问题以及urllib详解
Aug 03 Python
scrapy与selenium结合爬取数据(爬取动态网站)的示例代码
Sep 28 Python
浅谈tf.train.Saver()与tf.train.import_meta_graph的要点
May 26 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下一个阿拉伯数字转中文数字的函数
2007/07/16 PHP
一致性哈希算法以及其PHP实现详细解析
2013/08/24 PHP
PHP简单实现断点续传下载的方法
2015/09/25 PHP
深入浅出讲解:php的socket通信原理
2016/12/03 PHP
javascript编程起步(第六课)
2007/02/27 Javascript
jQuery弹出层插件简化版代码下载
2008/10/16 Javascript
关于jQuery中的end()使用方法
2011/07/10 Javascript
浅谈JS如何实现真正的对象常量
2017/06/25 Javascript
javascript、php关键字搜索函数的使用方法
2018/05/29 Javascript
为jquery的ajax请求添加超时timeout时间的操作方法
2018/09/04 jQuery
JS事件绑定的常用方式实例总结
2019/03/02 Javascript
layui 实现自动选择radio单选框(checked)的方法
2019/09/03 Javascript
解决vue 表格table列求和的问题
2019/11/06 Javascript
three.js利用gpu选取物体并计算交点位置的方法示例
2019/11/25 Javascript
[05:16]《大圣!大圣》——DOTA2新英雄齐天大圣配音李世宏老师专访
2016/12/13 DOTA
[45:15]Optic vs VP 2018国际邀请赛淘汰赛BO3 第一场 8.24
2018/08/25 DOTA
Python读写txt文本文件的操作方法全解析
2016/06/26 Python
Python中模块string.py详解
2017/03/12 Python
Python处理中文标点符号大集合
2018/05/14 Python
Python Django给admin添加Action的方法实例详解
2019/04/29 Python
HTML5: Web 标准最巨大的飞跃
2008/10/17 HTML / CSS
使用canvas对多图片拼合并导出图片的方法
2018/08/28 HTML / CSS
入党自我鉴定范文
2013/10/04 职场文书
在校硕士自我鉴定
2014/01/23 职场文书
企业内控岗位的职责
2014/02/07 职场文书
送温暖献爱心活动总结
2014/07/08 职场文书
小学生安全责任书
2014/07/25 职场文书
南京市纪委监察局整改方案
2014/09/16 职场文书
职工宿舍管理制度
2015/08/05 职场文书
大学生安全教育主题班会
2015/08/12 职场文书
2019送给家人们的中秋节祝福语
2019/08/15 职场文书
在HTML5 localStorage中存储对象的示例代码
2021/04/21 Javascript
linux下导入、导出mysql数据库命令的实现方法
2021/05/26 MySQL
Python字典和列表性能之间的比较
2021/06/07 Python
Python turtle实现贪吃蛇游戏
2021/06/18 Python
zabbix配置nginx监控的实现
2022/05/25 Servers