python3.4用循环往mysql5.7中写数据并输出
#!/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中写数据并输出的更多相关文章
- Linux启动kettle及linux和windows中kettle往hdfs中写数据(3)
在xmanager中的xshell运行进入图形化界面 sh spoon.sh 新建一个job
- IDEA中Spark往Hbase中写数据
import org.apache.hadoop.hbase.HBaseConfiguration import org.apache.hadoop.hbase.io.ImmutableBytesWr ...
- canal从mysql拉取数据,并以protobuf的格式往kafka中写数据
大致思路: canal去mysql拉取数据,放在canal所在的节点上,并且自身对外提供一个tcp服务,我们只要写一个连接该服务的客户端,去拉取数据并且指定往kafka写数据的格式就能达到以proto ...
- mapreduce 只使用Mapper往多个hbase表中写数据
只使用Mapper不使用reduce会大大减少mapreduce程序的运行时间. 有时候程序会往多张hbase表写数据. 所以有如题的需求. 下面给出的代码,不是可以运行的代码,只是展示driver中 ...
- JDBC向数据库中写数据
package MYSQK; import java.sql.*; /** * PreparedStatement 对象可以对sql语句进行预编译,预编译的信息会存在存储该对象中,当相同的sql语句再 ...
- VHDL testbench 例子,包含向文件中写数据
LIBRARY ieee; USE ieee.std_logic_1164.ALL; use std.textio.all; use ieee.std_logic_textio.all; EN ...
- 用C++向一个txt文档中写数据
bool CMaked::WriteFileMake(CString filePath, const char *isChange) { ofstream file; //filePath为该txt文 ...
- 利用copy函数简单快速输出/保存vector向量容器中的数据
如果要输出vector中的数据我们可以通过循环语句输出,更加简便的方法是利用copy函数直接输出,例子: #include "stdafx.h" #include <iost ...
- POI向Excel中写入数据及追加数据
import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import ...
随机推荐
- as3 程序域
问题我要在应用程序中载入其他域的swf文件,并且允许它访问程序中的 ActionScript 解决办法使用flash.system.Security.allowDomain( ), flash.sys ...
- C++ 实现的netstat -an 的功能<转>-目的为获取rtmp推流地址如果是域名的话查看1935的ip
目的可能是为了获取rtmp真正的推流ip 如果rtmp推流地址是域名,往CDN推流的话,需要nslookup 的那种DNS解析,然后获取的几个ip 可以使用netstat -n 等命令查看 1935 ...
- Kotlin语言学习笔记(6)
运算符重载(Operator overloading) 一元运算符 Expression Translated to +a a.unaryPlus() -a a.unaryMinus() !a a.n ...
- 批量压缩文件.net
C#调用 ICSharpCode.SharpZipLib.Zip 实现解压缩功能公用类 最近想用个解压缩功能 从网上找了找 加自己修改,个人感觉还是比较好用的,直接上代码如下 using System ...
- 全屏幕显示AVI
uses Unit2; procedure TForm1.Button1Click(Sender: TObject);begin Form2.Show; Form2.WindowState := ...
- struts2 参数注入 方法拦截器
web.xml: <?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi=" ...
- 数据类型-Series
数据类型-Series Series数据类型由一组数据和数据相关的索引组成,键 -> 值 Series数据类型可视为:一维 带标签 数组 Series基本操作类似数组和字典 Series数据类型 ...
- js中的变量提升(hoisting)
来看如下代码: function HelloJS(){ var array = [1,2,3,4,5]; for(var i in array){ } alert(i); } HelloJS(); a ...
- mybatis动态sql trim
trim标记是一个格式化的标记,可以完成set或者是where标记的功能,如下代码: 1. select * from user <trim prefix="WHERE" p ...
- Web标准:九、CSS表单设计
Web标准:九.CSS表单设计 知识点: 1.改变文本框和文本域样式 2.用图片美化按钮 3.改变下拉列表样式 4.用label标签提升用户体验 1)改变文本框和文本域样式 文本框标签:<i ...