平時的主要編程語言是Java,開發(fā)時也主要用Mysql,經(jīng)常為了測試,調(diào)試的目的需要操作數(shù)據(jù)庫,比如備份,插入測試數(shù)據(jù),修改測試數(shù)據(jù),有些時候不能簡單的用SQL就能完成任務(wù),或都很好的完成任務(wù),用Java寫又有點太麻煩了,就想到了Python。Python語法簡潔,不用編譯,可以經(jīng)較好的完成任務(wù)。今天看了下Python對Mysql的操作,做一下記錄。
首先,安裝需要的環(huán)境,Mysql和Python就不說了,必備的東西。
如果用Ubuntu,直接
sudo apt-get install python-mysqldb
安裝完成之后可以在Python解釋器中測試一下
輸入
Python代碼
import MySQLdb #注意大小寫!!
import MySQLdb #注意大小寫??! 如果不報錯,就證明安裝成功了,可能繼續(xù)了
MySQLdb在Python中也就相當于JAVA中的MySQL的JDBC Driver,Python也有類似的數(shù)據(jù)接口規(guī)范Python DB API,MySQLdb就是Mysql的實現(xiàn)。操作也比較簡單和其它平臺或語言操作數(shù)據(jù)庫一樣,就是建立和數(shù)據(jù)庫系統(tǒng)的連接,然后給數(shù)據(jù)庫輸入SQL,再從數(shù)據(jù)庫獲取結(jié)果。
先寫一個最簡單的,創(chuàng)建一個數(shù)據(jù)庫:
Python代碼
#!/usr/bin/env python
#coding=utf-8
###################################
# @author migle
# @date 2010-01-17
##################################
#MySQLdb 示例
#
##################################
import MySQLdb
#建立和數(shù)據(jù)庫系統(tǒng)的連接
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')
#獲取操作游標
cursor = conn.cursor()
#執(zhí)行SQL,創(chuàng)建一個數(shù)據(jù)庫.
cursor.execute("""create database python """)
#關(guān)閉連接,釋放資源
cursor.close();
#!/usr/bin/env python
#coding=utf-8
###################################
# @author migle
# @date 2010-01-17
##################################
#MySQLdb 示例
#
##################################
import MySQLdb
#建立和數(shù)據(jù)庫系統(tǒng)的連接
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')
#獲取操作游標
cursor = conn.cursor()
#執(zhí)行SQL,創(chuàng)建一個數(shù)據(jù)庫.
cursor.execute("""create database python """)
#關(guān)閉連接,釋放資源
cursor.close();
創(chuàng)建數(shù)據(jù)庫,創(chuàng)建表,插入數(shù)據(jù),插入多條數(shù)據(jù)
Python代碼
#!/usr/bin/env python
#coding=utf-8
###################################
# @author migle
# @date 2010-01-17
##################################
#MySQLdb 示例
#
##################################
import MySQLdb
#建立和數(shù)據(jù)庫系統(tǒng)的連接
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')
#獲取操作游標
cursor = conn.cursor()
#執(zhí)行SQL,創(chuàng)建一個數(shù)據(jù)庫.
cursor.execute("""create database if not exists python""")
#選擇數(shù)據(jù)庫
conn.select_db('python');
#執(zhí)行SQL,創(chuàng)建一個數(shù)據(jù)表.
cursor.execute("""create table test(id int, info varchar(100)) """)
value = [1,"inserted ?"];
#插入一條記錄
cursor.execute("insert into test values(%s,%s)",value);
values=[]
#生成插入?yún)?shù)值
for i in range(20):
values.append((i,'Hello mysqldb, I am recoder ' + str(i)))
#插入多條記錄
cursor.executemany("""insert into test values(%s,%s) """,values);
#關(guān)閉連接,釋放資源
cursor.close();
#!/usr/bin/env python
#coding=utf-8
###################################
# @author migle
# @date 2010-01-17
##################################
#MySQLdb 示例
#
##################################
import MySQLdb
#建立和數(shù)據(jù)庫系統(tǒng)的連接
conn = MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')
#獲取操作游標
cursor = conn.cursor()
#執(zhí)行SQL,創(chuàng)建一個數(shù)據(jù)庫.
cursor.execute("""create database if not exists python""")
#選擇數(shù)據(jù)庫
conn.select_db('python');
#執(zhí)行SQL,創(chuàng)建一個數(shù)據(jù)表.
cursor.execute("""create table test(id int, info varchar(100)) """)
value = [1,"inserted ?"];
#插入一條記錄
cursor.execute("insert into test values(%s,%s)",value);
values=[]
#生成插入?yún)?shù)值
for i in range(20):
values.append((i,'Hello mysqldb, I am recoder ' + str(i)))
#插入多條記錄
cursor.executemany("""insert into test values(%s,%s) """,values);
#關(guān)閉連接,釋放資源
cursor.close();
查詢和插入的流程差不多,只是多了一個得到查詢結(jié)果的步驟
Python代碼
#!/usr/bin/env python
#coding=utf-8
######################################
#
# @author migle
# @date 2010-01-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條記錄,注意由于之前執(zhí)行有了fetchone(),所以游標已經(jīng)指到第二條記錄了,也就是從第二條開始的所有記錄
print "只獲取5條記錄:"
results = cursor.fetchmany(5)
for r in results:
print r
print "獲取所有結(jié)果:"
#重置游標位置,0,為偏移量,mode=absolute | relative,默認為relative,
cursor.scroll(0,mode='absolute')
#獲取所有結(jié)果
results = cursor.fetchall()
for r in results:
print r
conn.close()
#!/usr/bin/env python
#coding=utf-8
######################################
#
# @author migle
# @date 2010-01-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條記錄,注意由于之前執(zhí)行有了fetchone(),所以游標已經(jīng)指到第二條記錄了,也就是從第二條開始的所有記錄
print "只獲取5條記錄:"
results = cursor.fetchmany(5)
for r in results:
print r
print "獲取所有結(jié)果:"
#重置游標位置,0,為偏移量,mode=absolute | relative,默認為relative,
cursor.scroll(0,mode='absolute')
#獲取所有結(jié)果
results = cursor.fetchall()
for r in results:
print r
conn.close()
從此學習網(wǎng)
http://www.congci.com