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程序中实现分布式进程的教程
Apr 28 Python
python win32 简单操作方法
May 25 Python
Python实现调度算法代码详解
Dec 01 Python
Python numpy生成矩阵、串联矩阵代码分享
Dec 04 Python
python获取网页中所有图片并筛选指定分辨率的方法
Mar 31 Python
Numpy之random函数使用学习
Jan 29 Python
使用Python计算玩彩票赢钱概率
Jun 26 Python
python能做哪方面的工作
Jun 15 Python
python获取系统内存占用信息的实例方法
Jul 17 Python
Python破解极验滑动验证码详细步骤
May 21 Python
tensorflow中的梯度求解及梯度裁剪操作
May 26 Python
python机器学习实现oneR算法(以鸢尾data为例)
Mar 03 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分页类代码
2013/04/02 PHP
php读取大文件示例分享(文件操作类)
2014/04/13 PHP
支持中文的PHP按字符串长度分割成数组代码
2015/05/17 PHP
PHP实现链表的定义与反转功能示例
2018/06/09 PHP
PHP利用pdo_odbc实现连接数据库示例【基于ThinkPHP5.1搭建的项目】
2019/05/13 PHP
jQuery实现的图片分组切换焦点图插件
2015/01/06 Javascript
JavaScript前补零操作实例
2015/03/11 Javascript
Bootstrap开发实战之第一次接触Bootstrap
2016/06/02 Javascript
获取JS中网页各种高宽与位置的方法总结
2016/07/27 Javascript
浅析location.href跨窗口调用函数
2016/11/22 Javascript
nodejs爬虫遇到的乱码问题汇总
2017/04/07 NodeJs
微信小程序实战之登录页面制作(5)
2020/03/30 Javascript
vue.js中toast用法及使用toast弹框的实例代码
2018/08/27 Javascript
微信小程序的mpvue框架快速上手指南
2019/05/15 Javascript
机器学习10大经典算法详解
2017/12/07 Python
python实现Adapter模式实例代码
2018/02/09 Python
详解Python中的分组函数groupby和itertools)
2018/07/11 Python
Python图像处理之颜色的定义与使用分析
2019/01/03 Python
Django框架模板介绍
2019/01/15 Python
详解Python数据分析--Pandas知识点
2019/03/23 Python
python实现画出e指数函数的图像
2019/11/21 Python
阿迪达斯荷兰官方网站:adidas荷兰
2018/03/16 全球购物
如何获得EntityManager
2014/02/09 面试题
计算机专业推荐信范文
2013/11/27 职场文书
电子工程求职信
2014/07/17 职场文书
总经理岗位职责说明书
2014/07/30 职场文书
办公室班子四风问题对照检查材料
2014/10/04 职场文书
2015元旦文艺汇演主持稿(开场白+结束语)
2014/12/14 职场文书
导游词欢迎词
2015/02/02 职场文书
幼儿教师年度个人总结
2015/02/05 职场文书
2015年学校信息技术工作总结
2015/05/25 职场文书
高中班主任培训心得体会
2016/01/07 职场文书
学生安全责任协议书
2016/03/22 职场文书
2019自荐信该如何写呢?
2019/07/05 职场文书
JavaWeb 入门:Hello Servlet
2021/07/16 Java/Android
vue-cil之axios的二次封装与proxy反向代理使用说明
2022/04/07 Vue.js