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使用scrapy抓取网站sitemap信息的方法
Apr 08 Python
Python字符串处理函数简明总结
Apr 13 Python
wxpython中自定义事件的实现与使用方法分析
Jul 21 Python
Python:Scrapy框架中Item Pipeline组件使用详解
Dec 27 Python
致Python初学者 Anaconda入门使用指南完整版
Apr 05 Python
python 删除列表里所有空格项的方法总结
Apr 18 Python
对python requests的content和text方法的区别详解
Oct 11 Python
在Python中实现shuffle给列表洗牌
Nov 08 Python
python实现简易数码时钟
Feb 19 Python
django 数据库 get_or_create函数返回值是tuple的问题
May 15 Python
Python如何输出百分比
Jul 31 Python
使用numpy nonzero 找出非0元素
May 14 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&amp;&amp;mysql)三
2006/10/09 PHP
php读取html并截取字符串的简单代码
2009/11/30 PHP
PHP计划任务、定时执行任务的实现代码
2011/04/23 PHP
php自动加载方式集合
2016/04/04 PHP
使用composer命令加载vendor中的第三方类库 的方法
2019/07/09 PHP
Yii框架多语言站点配置方法分析【中文/英文切换站点】
2020/04/07 PHP
javascript 点击整页变灰的效果(可做退出效果)。
2008/01/09 Javascript
Javascript中获取出错代码所在文件及行数的代码
2010/09/23 Javascript
关于onScroll事件在IE6下每次滚动触发三次bug说明
2011/09/21 Javascript
javascript基础知识大全 便于大家学习,也便于我自己查看
2012/08/17 Javascript
解析JavaScript中delete操作符不能删除的对象
2013/12/03 Javascript
快速解决jQuery与其他库冲突的方法介绍
2014/01/02 Javascript
在JavaScript中处理数组之reverse()方法的使用
2015/06/09 Javascript
jQuery基于BootStrap样式实现无限极地区联动
2016/08/26 Javascript
js实现短信发送倒计时功能(正则验证)
2017/02/10 Javascript
详解angular element()方法使用
2017/04/08 Javascript
jQuery Validate插件ajax方式验证输入值的实例
2017/12/21 jQuery
iview日期控件,双向绑定日期格式的方法
2018/03/15 Javascript
详解在vue-test-utils中mock全局对象
2018/11/07 Javascript
如何在Angular应用中创建包含组件方法示例
2019/03/23 Javascript
PYTHON 中使用 GLOBAL引发的一系列问题
2016/10/12 Python
Python字典操作详细介绍及字典内建方法分享
2018/01/04 Python
python获取指定日期范围内的每一天,每个月,每季度的方法
2019/08/08 Python
基于django 的orm中非主键自增的实现方式
2020/05/18 Python
Django返回HTML文件的实现方法
2020/09/17 Python
Canvas制作的下雨动画的示例
2018/03/06 HTML / CSS
Lookfantastic日本官网:英国知名护肤、化妆品和头发护理购物网站
2018/04/21 全球购物
女性时尚在线:IVRose
2019/02/23 全球购物
工程概预算专业毕业生求职信
2013/10/04 职场文书
电气工程及自动化专业自荐书范文
2013/12/18 职场文书
DIY蛋糕店的创业计划书范文
2013/12/26 职场文书
《油菜花开了》教学反思
2014/02/22 职场文书
纪念九一八事变演讲稿:牢记历史,捍卫主权
2014/09/14 职场文书
村级干部党员公开承诺事项
2015/05/04 职场文书
关于办理居住证的介绍信模板
2019/11/27 职场文书
关于Vue Router的10条高级技巧总结
2021/05/06 Vue.js