使用Python操控MySQL數據庫
1.MySQLdb的簡單示例
import MySQLdb
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd='xxx',db='xxx',port=3306)
cur=conn.cursor()
cur.execute('select * from user')
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
2.MySQL相關操作
其實Python下對MySQL進行操作和直接使用MySQL Shell的方法差不多,只是需要多寫幾條模板代碼而已。另外,記得最後commit()。
import MySQLdb
try:
conn = MySQLdb.connect(host='localhost',user='root',passwd='xxx',port=3306)
cur = conn.cursor()
cur.execute('create database if not exists test_db')
conn.select_db('test_db')
cur.execute('create table test_tb(id int,name char(20))')
#單條INSERT
cur.execute('INSERT INTO test_tb VALUES(%s,%s)',[1,'Elfsong'])
#批量INSERT
values=[]
for i in range(20):
values.append((i,'i'))
cur.executemany('INSERT INTO test_tb VALUES(%s,%s)',values)
#修改
cur.execute('UPDATA test_tb SET name = "Sony" WHERE id = 1')
conn.commit()
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
3.常用的函數
MySQL連接對象提供了對事務操作的支持,標準的方法:
commit() 提交
rollback() 回滾
cursor執行命令的方法:
callproc(self, procname, args) :用來執行存儲過程,接收的參數爲存儲過程名和參數列表,返回值爲受影響的行數
execute(self, query, args) :執行單條sql語句,接收的參數爲sql語句本身和使用的參數列表,返回值爲受影響的行數
executemany(self, query, args) :執行單挑sql語句,但是重複執行參數列表裏的參數,返回值爲受影響的行數
nextset(self): 移動到下一個結果集
cursor接收返回值的方法:
fetchall(self): 接收全部的返回結果行.
fetchmany(self, size=None): 接收size條返回結果行.如果size的值大於返回的結果行的數量,則會返回cursor.arraysize條數據.
fetchone(self): 返回一條結果行.
scroll(self, value, mode=’relative’): 移動指針到某一行.如果mode=’relative’,則表示從當前所在行移動value條,如果 mode=’absolute’,則表示從結果集的第一行移動value條.