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实现保存网页到本地示例
Mar 16 Python
python类继承与子类实例初始化用法分析
Apr 17 Python
Python实现优先级队列结构的方法详解
Jun 02 Python
python使用matplotlib库生成随机漫步图
Aug 27 Python
对python中Json与object转化的方法详解
Dec 31 Python
python实现Dijkstra算法的最短路径问题
Jun 21 Python
Python 把序列转换为元组的函数tuple方法
Jun 27 Python
python多环境切换及pyenv使用过程详解
Sep 27 Python
python实现Pyecharts实现动态地图(Map、Geo)
Mar 25 Python
python 操作mysql数据中fetchone()和fetchall()方式
May 15 Python
python实现邮件循环自动发件功能
Sep 11 Python
Opencv python 图片生成视频的方法示例
Nov 18 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
回帖脱衣服的图片实现代码
2014/02/15 PHP
Zend Framework教程之配置文件application.ini解析
2016/03/10 PHP
PHP生成及获取JSON文件的方法
2016/08/23 PHP
Laravel第三方包报class not found的解决方法
2019/10/13 PHP
JQuery.uploadify 上传文件插件的使用详解 for ASP.NET
2010/01/22 Javascript
js变量以及其作用域详解
2020/07/18 Javascript
EasyUi datagrid 实现表格分页
2015/02/10 Javascript
多个jQuery版本共存的处理方案
2015/03/17 Javascript
js实现select跳转菜单新窗口效果代码分享(超简单)
2015/08/21 Javascript
javascript中arguments,callee,caller详解
2016/03/16 Javascript
浅析jQuery中使用$所引发的问题
2016/05/29 Javascript
json对象转为字符串,当做参数传递时加密解密的实现方法
2016/06/29 Javascript
jQuery向父辈遍历的简单方法
2016/09/18 Javascript
JS基于for语句编写的九九乘法表示例
2018/01/04 Javascript
vue点击页面空白处实现保存功能
2019/11/06 Javascript
如何通过vscode运行调试javascript代码
2020/07/24 Javascript
[02:20]DOTA2亚洲邀请赛 IG战队出场宣传片
2015/02/07 DOTA
Python运算符重载用法实例
2015/05/28 Python
Python中http请求方法库汇总
2016/01/06 Python
Pycharm学习教程(2) 代码风格
2017/05/02 Python
python http接口自动化脚本详解
2018/01/02 Python
和孩子一起学习python之变量命名规则
2018/05/27 Python
使用Python正则表达式操作文本数据的方法
2019/05/14 Python
解决python中导入win32com.client出错的问题
2019/07/26 Python
python实现读取类别频数数据画水平条形图案例
2020/04/24 Python
python相对企业语言优势在哪
2020/06/12 Python
详解用selenium来下载小姐姐图片并保存
2021/01/26 Python
解决pycharm 格式报错tabs和space不一致问题
2021/02/26 Python
Yahoo-PHP面试题3
2012/01/14 面试题
2014党员四风对照检查材料思想汇报
2014/09/17 职场文书
上课迟到检讨书300字
2014/10/15 职场文书
2015年幼儿园中班开学寄语
2015/05/27 职场文书
2016年教师反腐倡廉心得体会
2016/01/13 职场文书
教师理论学习心得体会
2016/01/21 职场文书
Pytorch可视化的几种实现方法
2021/06/10 Python
i5-10400f处理相当于i7多少水平
2022/04/19 数码科技