#!/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. Redis基本操作-list

    Redis的5种数据结构:string.list.hash.set和zset; Redis 所有的数据结构都是以唯一的 key 字符串作为名称,然后通过这个唯一 key 值来获取相应的 value 数 ...

  2. NTP时间服务器搭建

    系统时区设置::: 查看当前时区# date -R修改系统时区# timeconfig  或# cp  /usr/share/zoneinfo/Asia/Shanghai  /etc/localtim ...

  3. Becoming inspired - ASC - 2017 MARCH 24

    Becoming inspired - The 11 questions to ask yourself when you feel uninspired @ Advanced Studio Clas ...

  4. 跨越数据库操作时注意要加dbo

    跨越数据库操作时注意要加dbo insert into hrdb.dbo.TB_B_PROJECTS  :这样是正确的 insert into hrdb.TB_B_PROJECTS  :这样是错误的

  5. XML文件的写,集合XML序列化(写)。XML文件的读,递归遍历

    XML文件:必须要有一个节点.检验xml文件,可以用浏览器打开,能打开表示对,否则错. 处理方法: DOM:XmlDocument文档对象模型 Sax(事件驱动,XmlReader) XmlSeria ...

  6. one by one 项目 part 3

    mysql error:Table 'performance_schema.session_variables' doesn't exist 打开cmd 输入:mysql_upgrade -u roo ...

  7. debug-stripped.ap_' specified for property 'resourceFile' does not exist.(转载)

    1.错误描述 更新Android Studio到2.0版本后,出现了编译失败的问题,我clean project然后重新编译还是出现抑郁的问题,问题具体描述如下所示: Error:A problem ...

  8. 解决windows 下mysql 表名自动转成小写的问题

    由于web用的是mvc,数据库用的是mysql.为了方便开发,在windows7下面也安装了个mysql,今天在创建表的时候,遇到了个棘手的问题.所有的表名都转成了小写,这不是我要的,作为处女座,是不 ...

  9. 个人总结-----非贪心算法的图的m着色判断及优化问题

    1.问题描述: 对于著名的图的m着色,有两个主要的问题,一个是图的m色判定问题,一个是图的m色优化问题,描述如下. 图的m色判定问题: 给定无向连通图G和m种颜色.用这些颜色为图G的各顶点着色.问是否 ...

  10. 修改hosts,***

    某些网站之所以在国内上不了,是因为dns受到干扰,无法解析出正确的ip地址. 可以在hosts文件中加入网站对应的正确ip地址,进行访问. 1.打开hosts文件,  路径为 C:\Windows\S ...