下載安裝mysql-connector
在命令行中執行下面的命令:
python -m pip install mysql-connector
如果是windows上面出錯的話,可以參考這篇博客:pip安裝模塊失敗的解決辦法
測試
進入python中,嘗試導入mysql.connector模塊,如果沒有報錯的話,就證明模塊已經成功安裝,可以使用了。
C:\WINDOWS\system32>python Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import mysql.connector >>>
連接MySQL
主要是使用mysql.connector模塊的connect函數,需要注意參數的名稱。
import mysql.connector # 接收參數:user, password, host, port=3306, unix_socket and database # 返回一個MySQLConnection Object conn = mysql.connector.connect( host='localhost', user='root', password='root', database='test' )
執行SQL命令
執行sql命令之前,需要先創建一個查詢,調用一下cursor()方法,這個方法名光標的意思,可以理解為,命令行中,執行sql語句之前,先要有一個光標行,在光標行中進行操作。
調用cursor()返回的結果就是光標行(cmd,簡稱cmd),然后調用cmd的execute()方法,傳入要執行的sql即可,不過需要注意的是,執行sql的結果,執行的結果仍舊保存在cmd中。
select查詢操作
執行select操作,使用fetchall()一次性取回所有的結果集。
import mysql.connector # 接收參數:user, password, host, port=3306, unix_socket and database # 返回一個MySQLConnection Object conn = mysql.connector.connect( host='localhost', user='root', password='root', database='test' ) # 創建一個查詢 cmd = conn.cursor() # 執行一條原生的SQL語句,執行結果保存在cmd中,沒有返回值 cmd.execute("select id, name, age from stu") # 可以使用fetchall(),獲取所有的查詢結果集,返回值為一個tuple,每一個元素是一個list res = cmd.fetchall() print(res) # [(1, 'LiMing', 20), (2, 'XiaoHua', 30), (3, 'LiLei', 10)]
執行select操作,使用fetchone()每次只取一條記錄
import mysql.connector conn = mysql.connector.connect( host='localhost', user='root', password='root', database='test' ) cmd = conn.cursor() cmd.execute("select id, name, age from stu") # 使用fetchone()返回一條結果集,每調用一次之后,內部指針會指向下一條結果集 print(cmd.fetchone()) # (1, 'LiMing', 20) print(cmd.fetchone()) # (2, 'XiaoHua', 30) print(cmd.fetchone()) # (3, 'LiLei', 10)
執行select操作,使用fetchmany(num)指定每次返回的num條結果集
import mysql.connector conn = mysql.connector.connect( host='localhost', user='root', password='root', database='test' ) cmd = conn.cursor() cmd.execute("select * from stu") res = cmd.fetchmany(2) # 指定返回2條記錄 print(res) # [(1, 'LiMing', 20), (2, 'XiaoHua', 30)] res = cmd.fetchmany(1) # 指定返回1條記錄 print(res) # [(3, 'LiLei', 10)]
insert、update、delete操作
insert、update、delete操作,也都是使用execute方法,只需要將要執行的sql語句傳入即可。
可以在執行增刪改操作之后,rowcount屬性保存着受影響的記錄數。
每次插入一條數據
import mysql.connector # 接收參數:user, password, host, port=3306, unix_socket and database # 返回一個MySQLConnection Object conn = mysql.connector.connect( host='localhost', user='root', password='root', database='test' ) # 創建一個查詢 cmd = conn.cursor() # 執行原生SQL語句 cmd.execute("insert into stu (id, name, age) values (4, 'LiBai', 99)") print(cmd.rowcount) # 1 cmd.execute("select * from stu") res = cmd.fetchall() print(res) # [(1, 'LiMing', 20), (2, 'XiaoHua', 30), (3, 'LiLei', 10), (4, 'LiBai', 99)]
使用預處理格式(占位符格式)
可以查看一下execute()方法的定義:
class MySQLCursor(CursorBase): ''' 省略很多方法和變量 ''' def execute(self, operation, params=None, multi=False): """Executes the given operation Executes the given operation substituting any markers with the given parameters. For example, getting all rows where id is 5: cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,)) The multi argument should be set to True when executing multiple statements in one operation. If not set and multiple results are found, an InterfaceError will be raised. If warnings where generated, and connection.get_warnings is True, then self._warnings will be a list containing these warnings. Returns an iterator when multi is True, otherwise None. """
第1個參數是要執行的SQL語句,其中,參數位置先使用占位符來占位
第2個參數是一個tuple(元組),元素值就是SQL占位符對應的參數,注意只有一個參數的時候,要寫成(xxx,),后面的逗號不要忘記。
第3個參數是一個bool值,表示第一個參數是不是多個SQL語句,如果是的話,就傳入True,否則傳入False。
使用示例
import mysql.connector conn = mysql.connector.connect( host='localhost', user='root', password='root', database='test' ) cmd = conn.cursor() # 注意,在SQL中的占位符,統一寫%s, 具體的類型,是在tuple中,傳入的參數元素類型決定 cmd.execute("select * from stu where id=%s and name=%s", (1, 'LiMing')) res = cmd.fetchall() print(res) # [(1, 'LiMing', 20)]