#!/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("发生异常")

学习的几个地方:

http://blog.csdn.net/nuli888/article/details/51960571

 #!/usr/bin/python3
import pymysql
import types db=pymysql.connect("localhost","root","","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))

http://www.runoob.com/python/python-mysql.html

http://www.cnblogs.com/lei0213/p/6002921.html

http://blog.csdn.net/magicbreaker/article/details/41811519

http://blog.csdn.net/bwlab/article/details/51146640

python3.4用循环往mysql5.7中写数据并输出的更多相关文章

  1. Linux启动kettle及linux和windows中kettle往hdfs中写数据(3)

    在xmanager中的xshell运行进入图形化界面 sh spoon.sh 新建一个job

  2. IDEA中Spark往Hbase中写数据

    import org.apache.hadoop.hbase.HBaseConfiguration import org.apache.hadoop.hbase.io.ImmutableBytesWr ...

  3. canal从mysql拉取数据,并以protobuf的格式往kafka中写数据

    大致思路: canal去mysql拉取数据,放在canal所在的节点上,并且自身对外提供一个tcp服务,我们只要写一个连接该服务的客户端,去拉取数据并且指定往kafka写数据的格式就能达到以proto ...

  4. mapreduce 只使用Mapper往多个hbase表中写数据

    只使用Mapper不使用reduce会大大减少mapreduce程序的运行时间. 有时候程序会往多张hbase表写数据. 所以有如题的需求. 下面给出的代码,不是可以运行的代码,只是展示driver中 ...

  5. JDBC向数据库中写数据

    package MYSQK; import java.sql.*; /** * PreparedStatement 对象可以对sql语句进行预编译,预编译的信息会存在存储该对象中,当相同的sql语句再 ...

  6. VHDL testbench 例子,包含向文件中写数据

      LIBRARY ieee; USE ieee.std_logic_1164.ALL; use std.textio.all; use ieee.std_logic_textio.all;   EN ...

  7. 用C++向一个txt文档中写数据

    bool CMaked::WriteFileMake(CString filePath, const char *isChange) { ofstream file; //filePath为该txt文 ...

  8. 利用copy函数简单快速输出/保存vector向量容器中的数据

    如果要输出vector中的数据我们可以通过循环语句输出,更加简便的方法是利用copy函数直接输出,例子: #include "stdafx.h" #include <iost ...

  9. POI向Excel中写入数据及追加数据

    import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import ...

随机推荐

  1. ABAP-动态创建DATABASE/FUNCTION(风险)

    警告:此程序仅供研究,请谨慎操作,切勿对系统标准数据表及功能函数进行测试(可能无法修复). 程序:EWUCINS REPORT EWUCINS MESSAGE-ID US NO STANDARD PA ...

  2. UI5-文档-4.11-Pages and Panels

    在完成了应用程序结构的所有工作之后,是时候改进我们的应用程序的外观了.在这一步中,您还将了解控件聚合. Preview A panel is now displaying the controls f ...

  3. jenkins 修改工作目录

    修改Jenkins路径 Jenkins的默认安装路径是/var/lib/jenkins 现在由于这个根目录的磁盘太小,所以切换到/data 目录下. Jenkins目录.端口.工作目录等信息在/etc ...

  4. 【348】通过 Numpy 创建各式各样的矩阵

    参考:NumPy之array-一个程序媛的自我修养-51CTO博客 参考:numpy中数组和矩阵的区别 - jiangsujiangjiang的博客 - CSDN博客 一.使用系统方法 二.用指定的数 ...

  5. python判断unicode是否是汉字,数字,英文,或者其他字符

    下面这个小工具包含了 判断unicode是否是汉字,数字,英文,或者其他字符. 全角符号转半角符号. unicode字符串归一化等工作. 还有一个能处理多音字的汉字转拼音的程序,还在整理中. #!/u ...

  6. python函数式编程(转)

    函数式编程是使用一系列函数去解决问题,按照一般编程思维,面对问题时我们的思考方式是“怎么干”,而函数函数式编程的思考方式是我要“干什么”. 至于函数式编程的特点暂不总结,我们直接拿例子来体会什么是函数 ...

  7. SQL 数据库 子查询及示例

    子查询,又叫做嵌套查询. 将一个查询语句做为一个结果集供其他SQL语句使用,就像使用普通的表一样,被当作结果集的查询语句被称为子查询. 子查询有两种类型: 一种是只返回一个单值的子查询,这时它可以用在 ...

  8. Electron Browser加载iframe(webview src属性)

    browser或者webcontents 的高度与宽度比例对webview中src的页面结构也是有一定影响的

  9. js中的变量提升(hoisting)

    来看如下代码: function HelloJS(){ var array = [1,2,3,4,5]; for(var i in array){ } alert(i); } HelloJS(); a ...

  10. android热门消息推送横向测评![转]

    关于这个话题,已经不是什么新鲜事了.对于大多数中小型公司一般都是选择第三方的服务来实现.但是现在已经有很多提供推送服务的公司和产品,如何选择一个适合自己项目的服务呢?它们之间都有什么差别?在此为大家做 ...