標籤:localhost python version except cursor
本文介紹了Python操作mysql,執行SQL語句,擷取結果集,遍曆結果集,取得某個欄位,擷取表欄位名,將圖片插入資料庫,執行事務等各種代碼執行個體和詳細介紹。
執行個體1、擷取MYSQL的版本
#!/usr/bin/env python import MySQLdb as mdb try: con=mdb.connect(‘localhost‘,‘root‘,‘123‘,‘test‘) #串連mysql的方法 cur=con.cursor() #所有的查詢,都在串連con的一個模組cursor上面啟動並執行 cur.execute(‘SELECT VERSION()‘) #執行一個查詢 data = cur.fetchone() #取得上面查詢的結果,是單個結果 cur.close() #關閉 print "Database version:%s" %data con.close() except mdb.Error: print "Mysql Error %d: %s" % (e.args[0], e.args[1])
執行個體2、建立一個表並且插入輸入
#!/usr/bin/env python
import MySQLdb as mdb
try:
con=mdb.connect(‘localhost‘,‘root‘,‘123‘,‘test‘)
cur=con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
cur.execute("INSERT INTO Writers(Name) VALUES(‘Jack London‘)")
cur.execute("INSERT INTO Writers(Name) VALUES(‘Honore de Balzac‘)")
cur.execute("INSERT INTO Writers(Name) VALUES(‘Lion Feuchtwanger‘)")
cur.execute("INSERT INTO Writers(Name) VALUES(‘Emile Zola‘)")
cur.execute("INSERT INTO Writers(Name) VALUES(‘Truman Capote‘)")
except mdb.Error:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
運行結果,登陸資料庫進行查看
mysql> select * from Writers;
+----+-------------------+
| Id | Name |
+----+-------------------+
| 1 | Jack London |
| 2 | Honore de Balzac |
| 3 | Lion Feuchtwanger |
| 4 | Emile Zola |
| 5 | Truman Capote |
+----+-------------------+
執行個體3、python使用select擷取mysql的資料並遍曆
#!/usr/bin/env python
import MySQLdb as mdb
try:
con=mdb.connect(‘localhost‘,‘root‘,‘123‘,‘test‘)
cur=con.cursor()
cur.execute("SELECT * FROM Writers")
rows = cur.fetchall() #使用fetchall函數,將結果集(多維元組)存入rows裡面
for row in rows: #依次遍曆結果集,發現每個元素,就是表中的一條記錄,用一個元組來顯示
print row
except mdb.Error:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
運行結果
(1L, ‘Jack London‘)
(2L, ‘Honore de Balzac‘)
(3L, ‘Lion Feuchtwanger‘)
(4L, ‘Emile Zola‘)
(5L, ‘Truman Capote‘)
上面的代碼,用來將所有的結果取出,不過列印的時候是每行一個元組列印,現在我們使用方法,取出其中的單個資料。
#!/usr/bin/env python
import MySQLdb as mdb
try:
con=mdb.connect(‘localhost‘,‘root‘,‘123‘,‘test‘)
cur=con.cursor()
cur.execute("SELECT * FROM Writers")
numrows = int(cur.rowcount) #使用cur.rowcount擷取結果集的條數
for i in range(numrows): #迴圈numbrows次,每次取出一行資料
row = cur.fetchone() #每次取出一行,放到row中,這是一個元組(id,name)
print row[0],row[1] #直接輸出兩個元素
except mdb.Error:
print "Mysql Error %d: %s" % (e.args[0], e.args[1]
運行結果
1 Jack London
2 Honore de Balzac
3 Lion Feuchtwanger
4 Emile Zola
5 Truman Capote
本文出自 “伺服器” 部落格,請務必保留此出處http://zhangfang2012.blog.51cto.com/6380212/1633937
python操作Mysql執行個體