一、python操作數據庫
1.格式:大概分爲三部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 代碼
import MySQLdb
conn = MySQLdb.connect(host = '192.168.0.180' ,user = 'cattle' ,passwd = 'cattle' ,db = 'cattle' )
cur = conn.cursor() #創建連接
reCount = cur.execute( 'select * from admin' )
data = cur.fetchall() #對數據進行操作
cur.close() #關閉連接
conn.close()
print data
print reCount #這個的意思是執行完這條命令影響的條數
結果
(( 1L , 'n2' , 'a2' ), ( 2L , 'n1' , 'a1' ))
2
|
1.連接的建立與釋放
建立連接時可用connect函數,它返回一個connection類型對象
1 | db = MySQLdb.connect(host = '192.168.0.180' ,user = 'cattle' ,passwd = 'cattle' ,db = 'cattle' )
|
connect常用的參數:
host:數據庫主機名.默認是用本地主機
user:數據庫登陸名.默認是當前用戶
passwd:數據庫登陸的祕密.默認爲空
db: 要使用的數據庫名.沒有默認值
port:MySQL服務使用的TCP端口.默認是3306
charset:數據庫編碼
如果在數據編碼設置正確時,向數據庫插入數據出現亂碼時,可以設置連接的字符集參數
釋放連接時可以用connection類型對象的close方法
2.cursor對象
執行SQL語句前要獲得一個指定連接的cursor對象,由cursor對象對象執行SQL查詢並獲得結果
獲得cursor對象的方法
在默認情況下cursor方法返回的是BaseCursor類型對象,BaseCursor類型對象在執行查詢後每條記錄的結果以列表(list)表示。如果要返回字典(dict)表示的記錄,就要設置cursorclass參數爲MySQLdb.cursors.DictCursor類
1 | cur = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
|
3.插入、刪除、更新、查詢等操作
cursor類型提供了execute方法用於執行SQL語句
3.1查詢
1 | cur.execute( 'select * from admin' )
|
3.2獲取結果
獲取結果有三種方式:fetchone、fetchall、fetchmany,返回結果是tuple,tuple中每一個元素對應查詢結果中的一條記錄
fetchone()返回結果集中的第一條記錄
fetchall()返回結果集中的所有記錄
fetchmany([size])返回結果集中的size條記錄
3.3插入
由於SQL語句較長所以可以將SQL語句定義成變量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import MySQLdb
conn = MySQLdb.connect(host = '192.168.0.180' ,user = 'cattle' ,passwd = 'cattle' ,db = 'cattle' )
cur = conn.cursor()
sql = "insert into admin (name,address) values(%s,%s)" #name和address相當於key,%s是佔位符
params = ( 'n4' , 'a4' ) #n4和a4相當於value,寫在佔位符的位置
reCount = cur.execute(sql,params)
conn.commit() #執行完增加、刪除、更改的動作都得執行這步進行提交才能生效
cur.close()
conn.close()
print reCount
|
3.4刪除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import MySQLdb
conn = MySQLdb.connect(host = '192.168.0.180' ,user = 'cattle' ,passwd = 'cattle' ,db = 'cattle' )
cur = conn.cursor()
sql = "delete from admin where id = %s"
params = ( 1 )
reCount = cur.execute(sql,params)
conn.commit()
cur.close()
conn.close()
print reCount
|
3.5更改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import MySQLdb
conn = MySQLdb.connect(host = '192.168.0.180' ,user = 'cattle' ,passwd = 'cattle' ,db = 'cattle' )
cur = conn.cursor()
sql = "update admin set name = %s where id = 8"
params = ( 'n8' )
reCount = cur.execute(sql,params)
conn.commit()
cur.close()
conn.close()
print reCount
|
4.事務
python操作數據庫的時候一旦有錯誤不提交操作,全部都沒問題的時候才提交