python數據庫操作常用功能使用詳解(創建表/插入數據/獲取數據)


實例1、取得MYSQL版本

# -*- coding: UTF-8 -*- #安裝MYSQL DB for python
import MySQLdb as mdb con = None try: #連接mysql的方法:connect(host='localhost',user='root',passwd='root',db='test',port=3306)
    con = mdb.connect('localhost', 'root', 'root', 'test'); #所有的查詢,都在連接con的一個模塊cursor上面運行的
    cur = con.cursor() #執行一個查詢
    cur.execute("SELECT VERSION()") #取得上個查詢的結果,是單個結果
    data = cur.fetchone() print "Database version : %s " % data finally: if con: #無論如何,連接記得關閉
        con.close()

執行結果:

Database version : 5.5.25

 

 

實例2、創建一個表並且插入數據

# -*- coding: UTF-8 -*-
import MySQLdb as mdb import sys #將con設定為全局連接
con = mdb.connect('localhost', 'root', 'root', 'test'); with con: #獲取連接的cursor,只有獲取了cursor,我們才能進行各種操作
    cur = con.cursor() #創建一個數據表 writers(id,name)
    cur.execute("CREATE TABLE IF NOT EXISTS \ Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))") #以下插入了5條數據
    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')")

 實例3、拼接插入SQL數據

 
 1 import MySQLdb
 2 conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',db='test2',)
 3 cur = conn.cursor()
 4 sql = "insert into admin (name,addres) values (%s,%s)" 
 5 params = ('zhang','san')
 6 #sql = "insert into table(key1,key2,key3) values (%s,%s,%s)"%(value1,value2,value3)
 7 temp=cur.execute(sql,params)
 8 conn.commit()
 9 recount = cur.execute('select *from admin')
10 rows = cur.fetchall()
11 
12 cur.close()
13 conn.close()
14 for time in rows:
15  #print temp #查看影響條目
16  #print rows #查看數據庫表內容
17  print time  
View Code

結果:

(1L, 'hejin', 'USA')
(2L, 'jctang', 'usa')
(5L, 'zhang', 'san')

 

實例4、python使用slect獲取mysql的數據並遍歷

# -*- coding: UTF-8 -*-
import MySQLdb as mdb import sys #連接mysql,獲取連接的對象
con = mdb.connect('localhost', 'root', 'root', 'test'); with con: #仍然是,第一步要獲取連接的cursor對象,用於執行查詢
    cur = con.cursor() #類似於其他語言的query函數,execute是python中的執行查詢函數
    cur.execute("SELECT * FROM Writers") #使用fetchall函數,將結果集(多維元組)存入rows里面
    rows = cur.fetchall() #依次遍歷結果集,發現每個元素,就是表中的一條記錄,用一個元組來顯示
    for row in rows: print row
執行結果:
(1L, ‘Jack London')
(2L, ‘Honore de Balzac')
(3L, ‘Lion Feuchtwanger')
(4L, ‘Emile Zola')
(5L, ‘Truman Capote')

 

實例5、使用字典cursor取得結果集(可以使用表字段名字訪問值)

import MySQLdb as mdb
import sys
#獲得mysql查詢的鏈接對象
con = mdb.connect('localhost', 'root', '123456', 'test2')
with con:
#獲取連接上的字典cursor,注意獲取的方法,
#每一個cursor其實都是cursor的子類
cur = con.cursor(mdb.cursors.DictCursor)
#執行語句不變
cur.execute("select *from admin")
#獲取數據方法不變
rows = cur.fetchall()
#遍歷數據也不變(比上一個更直接一點)
for row in rows:
#這里,可以使用鍵值對的方法,由鍵名字來獲取數據

print '%s %s %s' %(row['id'],row['name'],row['addres'])
View Code

 

 結果:

10 zhang san
11 zhang san
12 zhang san
13 zhang san
14 zhang san
15 zhang san

      

 

實例6、獲取單個表的字段名和信息的方法


# -*- coding: UTF-8 -*-
import MySQLdb as mdb import sys #獲取數據庫的鏈接對象
con = mdb.connect('localhost', 'root', 'root', 'test') with con: #獲取普通的查詢cursor
    cur = con.cursor() cur.execute("SELECT * FROM Writers") rows = cur.fetchall() #獲取連接對象的描述信息
    desc = cur.description print 'cur.description:',desc #打印表頭,就是字段名字
    print "%s %3s" % (desc[0][0], desc[1][0]) for row in rows: #打印結果
        print "%2s %3s" % row 
運行結果: cur.description: ((‘Id', 3, 1, 11, 11, 0, 0), (‘Name', 253, 17, 25, 25, 0, 1))
Id Name
1 Jack London
2 Honore de Balzac
3 Lion Feuchtwanger
4 Emile Zola
5 Truman Capote

 


實例7、使用Prepared statements執行查詢(更安全方便)

 

# -*- coding: UTF-8 -*-
import MySQLdb as mdb import sys con = mdb.connect('localhost', 'root', 'root', 'test') with con: cur = con.cursor() #我們看到,這里可以通過寫一個可以組裝的sql語句來進行
    cur.execute("UPDATE Writers SET Name = %s WHERE Id = %s", ("Guy de Maupasant", "4")) #使用cur.rowcount獲取影響了多少行
    print "Number of rows updated: %d" % cur.rowcount

結果:

Number of rows updated: 1 
 
實例 8 刪除某一列SQL數據
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',db='test2',)
cur = conn.cursor()
sql = "delete from admin where id=%s"
params = ('2')
cur.execute(sql,params)
conn.commit()
cur.close()
conn.close()
View Code

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM