Python 操作Mysql

jopen 13年前發布 | 51K 次閱讀 Python Python開發

首先,安裝需要的環境,Mysql和Python就不說了,必備的東西。</span>


主要是安裝的MySQLdb,可以去sf.net下載,具體地址是http://sourceforge.net/projects/mysql-python/


如果用Ubuntu,直接

sudo apt-get install python-mysqldb

安裝完成之后可以在Python解釋器中測試一下

輸入

Python代碼  

import MySQLdb #注意大小寫!!  

如果不報錯,就證明安裝成功了,可能繼續了

MySQLdb在Python中也就相當于JAVA中的MySQL的JDBC Driver,Python也有類似的數據接口規范Python DB API,MySQLdb就是Mysql的實現。操作也比較簡單和其它平臺或語言操作數據庫一樣,就是建立和數據庫系統的連接,然后給數據庫輸入SQL,再從數據庫獲取結果。

先寫一個最簡單的,創建一個數據庫:

#!/usr/bin/env python  
#coding=utf-8  
###################################  
# @author  peng  
# @date 2012-05-17  
##################################  
#MySQLdb 示例  
#  
##################################  
import MySQLdb  
#建立和數據庫系統的連接  
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')  
#獲取操作游標  
cursor = conn.cursor()  
#執行SQL,創建一個數據庫.  
cursor.execute("""create database python """)  
#關閉連接,釋放資源  
cursor.close(); 

創建數據庫,創建表,插入數據,插入多條數據

#!/usr/bin/env python  
#coding=utf-8  
###################################  
# @author  peng  
# @date 2012-05-17  
##################################  
#MySQLdb 示例  
#  
##################################  
import MySQLdb  
#建立和數據庫系統的連接  
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')  
#獲取操作游標  
cursor = conn.cursor()  
#執行SQL,創建一個數據庫.  
cursor.execute("""create database if not exists python""")  
#選擇數據庫  
conn.select_db('python');  
#執行SQL,創建一個數據表.  
cursor.execute("""create table test(id int, info varchar(100)) """)  
value = [1,"inserted ?"];  
#插入一條記錄  
cursor.execute("insert into test values(%s,%s)",value);  
values=[]  
#生成插入參數值  
for i in range(20):  
    values.append((i,'Hello mysqldb, I am recoder ' + str(i)))  
#插入多條記錄  
cursor.executemany("""insert into test values(%s,%s) """,values);  
#關閉連接,釋放資源  
cursor.close();  

查詢和插入的流程差不多,只是多了一個得到查詢結果的步驟

#!/usr/bin/env python  
#coding=utf-8  
######################################  
#  
# @author  peng  
# @date 2012-05-17  
#  
######################################  
#  
# MySQLdb 查詢  
#  
#######################################  

import MySQLdb  
conn = MySQLdb.connect(host='localhost', user='root', passwd='longforfreedom',db='python')  
cursor = conn.cursor()  
count = cursor.execute('select * from test')  
print '總共有 %s 條記錄',count  
#獲取一條記錄,每條記錄做為一個元組返回  
print "只獲取一條記錄:"  
result = cursor.fetchone();  
print result  
#print 'ID: %s   info: %s' % (result[0],result[1])  
print 'ID: %s   info: %s' % result   
#獲取5條記錄,注意由于之前執行有了fetchone(),所以游標已經指到第二條記錄了,也就是從第二條開始的所有記錄  
print "只獲取5條記錄:"  
results = cursor.fetchmany(5)  
for r in results:  
    print r  
print "獲取所有結果:"  
#重置游標位置,0,為偏移量,mode=absolute | relative,默認為relative,  
cursor.scroll(0,mode='absolute')  
#獲取所有結果  
results = cursor.fetchall()  
for r in results:  
    print r  
conn.close() 


 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!