——MySQLdb模塊
常用的函數:
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):返回一條結果行
1.MySQLdb模塊的安裝方法之一
[root@YunWei-129 ~]# easy_install mysql-python
2.MySQLdb模塊實例用的表信息
MariaDB [easy]> desc student; +-------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | name | varchar(20) | YES | | NULL | | | sex | varchar(4) | YES | | NULL | | +-------+-------------+------+-----+---------+-------+ 3 rows in set (0.00 sec)
3.MySQLdb模塊的連接與查詢
# -*- coding: utf-8 -*- #! /usr/bin/env python import MySQLdb #連接數據庫 connect = MySQLdb.connect(host="localhost", user="root", passwd="12345", db="easy", port=3306, charset="utf8") #創建遊標 cursor = connect.cursor() #執行SQL語句 SQL = cursor.execute("select * from student;") #接收執行結果 EXE = cursor.fetchall() #打印執行結果 for SQL in EXE: print "ID : %-5s NAME : %-5s SEX : %-5s"% (SQL[0],SQL[1],SQL[2]) #關閉遊標 cursor.close() #關閉連接 connect.close()
4.MySQLdb模塊的插入與更新
# -*- coding: utf-8 -*- #! /usr/bin/env python import MySQLdb #連接數據庫 connect = MySQLdb.connect(host="localhost", user="root", passwd="12345", db="easy", port=3306, charset="utf8") #創建遊標 cursor = connect.cursor() #執行insert SQL語句 SQL_INSERT = cursor.execute("insert into student values(2,'小李','男');") #執行update SQL語句 SQL_UPDATE = cursor.execute("update student set name='小洋',sex='女' where id=1;") #執行select SQL語句 SQL_SELECT = cursor.execute("select * from student;") EXE = cursor.fetchall() #打印查看結果 for SQL in EXE: print "ID : %-5s NAME : %-5s SEX : %-5s"% (SQL[0],SQL[1],SQL[2]) #提交 connect.commit() #關閉遊標 cursor.close() #關閉連接 connect.close()
5.MySQLdb模塊的批量插入 [有很多方法,方法之一]
(1.創建一個新文本,添加需要寫入數據庫的信息 [每列用空格隔開]
[root@YunWei-129 ~]# cat info.txt 3 小陽 男 4 小小 女 5 小米 女 6 小南 男
(2.批量插入
# -*- coding: utf-8 -*- #! /usr/bin/env python import MySQLdb #打開文本 touch = file('/root/info.txt') #連接數據庫 connect = MySQLdb.connect(host="localhost", user="root", passwd="12345", db="easy", port=3306, charset="utf8") #創建遊標 cursor = connect.cursor() #執行insert SQL語句 for info in touch.readlines(): ID,NAME,SEX = info.split() cursor.execute("insert into student values(%d,'%s','%s');"% (int(ID),NAME,SEX)) #執行select SQL語句 SQL_SELECT = cursor.execute("select * from student;") EXE = cursor.fetchall() #打印查看結果 for SQL in EXE: print "ID : %-5s NAME : %-5s SEX : %-5s"% (SQL[0],SQL[1],SQL[2]) #提交 connect.commit() #關閉遊標 cursor.close() #關閉連接 connect.close()