如下所示:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "blzhu"
"""
python study
Date:2017
"""
import pymysql
# import MySQLdb #python2中的產(chǎn)物
try:
# 獲取一個(gè)數(shù)據(jù)庫(kù)連接,注意如果是UTF-8類型的,需要制定數(shù)據(jù)庫(kù)
conn = pymysql.connect(host='localhost', user='root', passwd='root', db='zbltest1', port=3306, charset='utf8')
cur = conn.cursor() # 獲取一個(gè)游標(biāo)
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()# 將數(shù)據(jù)寫入數(shù)據(jù)庫(kù)
# 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')")#錯(cuò)誤
#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函數(shù)轉(zhuǎn)義
print("ID: " + str(d[0]) + ' 名字: ' + d[1] + " 性別: " + d[2])
print("row_number:", (cur.rownumber))
# print('hello')
cur.close() # 關(guān)閉游標(biāo)
conn.close() # 釋放數(shù)據(jù)庫(kù)資源
except Exception:
print("發(fā)生異常")
上面代碼是對(duì)的,但是是曲折的。
下面整理一下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "blzhu"
"""
python study
Date:2017
"""
import pymysql
try:
# 獲取一個(gè)數(shù)據(jù)庫(kù)連接,注意如果是UTF-8類型的,需要制定數(shù)據(jù)庫(kù)
conn = pymysql.connect(host='localhost', user='root', passwd='root', db='zbltest1', port=3306, charset='utf8')
cur = conn.cursor() # 獲取一個(gè)游標(biāo)
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()# 將數(shù)據(jù)寫入數(shù)據(jù)庫(kù)
cur.execute('select * from student')
# data=cur.fetchall()
for d in cur:
# 注意int類型需要使用str函數(shù)轉(zhuǎn)義
print("ID: " + str(d[0]) + ' 名字: ' + d[1] + " 性別: " + d[2])
print("row_number:", (cur.rownumber))
# print('hello')
cur.close() # 關(guān)閉游標(biāo)
conn.close() # 釋放數(shù)據(jù)庫(kù)資源
except Exception:
print("發(fā)生異常")
#!/usr/bin/python3
import pymysql
import types
db=pymysql.connect("localhost","root","123456","python");
cursor=db.cursor()
#創(chuàng)建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插入數(shù)據(jù)
sql="""INSERT INTO `user` (`name`, `age`) VALUES
('test1', 1),
('test2', 2),
('test3', 3),
('test4', 4),
('test5', 5),
('test6', 6);"""
try:
# 執(zhí)行sql語(yǔ)句
cursor.execute(sql)
# 提交到數(shù)據(jù)庫(kù)執(zhí)行
db.commit()
except:
# 如果發(fā)生錯(cuò)誤則回滾
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])) #打印變量類型
print ("name=%s,age=%s" % \
(age, name))
以上這篇python3.4用循環(huán)往mysql5.7中寫數(shù)據(jù)并輸出的實(shí)現(xiàn)方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

