python使用MySQLdb模塊連接MySQL


1.安裝驅動

目前有兩個MySQL的驅動,我們可以選擇其中一個進行安裝:

MySQL-python:是封裝了MySQL C驅動的Python驅動;mysql-connector-python:是MySQL官方的純Python驅動。

MySQL-python:

安裝教程:http://www.cnblogs.com/jfl-xx/p/7299221.html

mysql-connector-python:

安裝教程:http://www.cnblogs.com/Bgod/p/6995601.html

2.測試連接

這里使用MySQL-python驅動,即MySQLdb模塊。

test_connect.py

 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 
 4 import MySQLdb
 5 
 6 # 打開數據庫連接
 7 db = MySQLdb.connect("localhost", "root", "123456", "test")
 8 
 9 # 使用cursor()方法獲取操作游標
10 cursor = db.cursor()
11 
12 # 使用execute方法執行SQL語句
13 cursor.execute("SELECT VERSION()")
14 
15 # 使用 fetchone() 方法獲取一條數據庫。
16 data = cursor.fetchone()
17 
18 print "Database version : %s " % data
19 
20 # 關閉數據庫連接
21 db.close()

測試結果如下,連接成功:

3.創建數據庫表

測試成功后,我們可以在python中直接為MySQL創建表:

create_table.py

 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 
 4 import MySQLdb
 5 
 6 # 打開數據庫連接
 7 db = MySQLdb.connect("localhost", "root", "123456", "test")
 8 
 9 # 使用cursor()方法獲取操作游標
10 cursor = db.cursor()
11 
12 # 如果數據表已經存在使用 execute() 方法刪除表。
13 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
14 
15 # 創建數據表SQL語句
16 sql = """CREATE TABLE EMPLOYEE (
17          FIRST_NAME  CHAR(20) NOT NULL,
18          LAST_NAME  CHAR(20),
19          AGE INT,  
20          SEX CHAR(1),
21          INCOME FLOAT )"""
22 
23 cursor.execute(sql)
24 
25 # 關閉數據庫連接
26 db.close()

建表結果 如下:

4.操作數據庫表

注意點:MySQL中的占位符為%s

operate_table.js

 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 
 4 import MySQLdb
 5 
 6 # 打開數據庫連接
 7 db = MySQLdb.connect("localhost", "root", "123456", "test")
 8 
 9 # 使用cursor()方法獲取操作游標
10 cursor = db.cursor()
11 
12 # SQL插入語句
13 ins_sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
14          LAST_NAME, AGE, SEX, INCOME)
15          VALUES ('yu', 'jie', 20, 'M', 8000)"""
16 
17 ins_sql1 = 'insert into employee(first_name, last_name, age, sex, income) values (%s, %s, %s, %s, %s)'
18 
19 # SQL查詢語句
20 sel_sql = 'select * from employee where first_name = %s'
21 
22 # SQL更新語句
23 upd_sql = 'update employee set age = %s where sex = %s'
24 
25 # SQL刪除語句
26 del_sql = 'delete from employee where first_name = %s'
27 
28 try:
29     # 執行sql語句
30     # insert
31     cursor.execute(ins_sql)
32     cursor.execute(ins_sql1, ('xu', 'f', 20, 'M', 8000))
33     # select
34     cursor.execute(sel_sql, ('yu',))
35     values = cursor.fetchall()
36     print values
37     # update
38     cursor.execute(upd_sql, (24, 'M',))
39     # delete
40     cursor.execute(del_sql, ('xu',))
41 
42     # 提交到數據庫執行
43     db.commit()
44 except:
45     # 發生錯誤時回滾
46     db.rollback()
47 
48 # 關閉數據庫連接
49 db.close()

 執行插入操作

執行查詢操作

執行更新操作

執行刪除操作

 

查詢語句的知識點:

Python查詢Mysql使用 fetchone() 方法獲取單條數據, 使用fetchall() 方法獲取多條數據。

fetchone(): 該方法獲取下一個查詢結果集。結果集是一個對象

fetchall():接收全部的返回結果行.

例如該例子:

 1 sel_sql = 'select * from employee where first_name = %s'
 2 cursor.execute(sel_sql, ('yu',))
 3     results = cursor.fetchall()
 4     for row in results:
 5         fname = row[0]
 6         lname = row[1]
 7         age = row[2]
 8         sex = row[3]
 9         income = row[4]
10         print "fname=%s, lname=%s,age=%d,sex=%s,income=%d" % (fname, lname, age, sex, income)

結果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM