Python3連接MySQL數據庫

Python 2.x 上鍊接MySQL的庫卻是很多的,其中比較著名就是MySQLdb(Django項目都使用它;我也在開發測試系統時也使用過),見:http://sourceforge.net/projects/mysql-python/html

不過,目前MySQLdb並不支持python3.x,網上找了一些方法,後來我仍是偶然發現MySQL官方已經提供了MySQL鏈接器,並且已經有支持Python3.x的版本了。MySQL Connector/Python, a self-contained Python driver for communicating with MySQL servers. 這個用起來仍是感受比較順手的。
關於MySQL Connector/Python的各類介紹、安裝、API等文檔,仍是參考官網吧:http://dev.mysql.com/doc/connector-python/en/index.html
(注意:安裝程序將關於MySQL Connnector的python2的源文件複製到了python3庫的位置(運行時會報語法錯誤),我就直接手動複製了其中python3/目錄下的文件過去就解決。)python

另外,Python3.x鏈接MySQL的其餘方案有:oursql, PyMySQL, myconnpy 等,參考以下連接:mysql

http://packages.python.org/oursql/git

https://github.com/petehunt/PyMySQL/github

https://launchpad.net/myconnpysql

下面只是貼一個試用 MySQL Connector/Python 的Python腳本吧(包括建立表、插入數據、從文件讀取並插入數據、查詢數據等):
python3.x

View Code PYTHON
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/python3
# a sample to use mysql-connector for python3
# see details from   http://dev.mysql.com/doc/connector-python/en/index.html
 
import mysql.connector
import sys, os
 
user = 'root'
pwd  = '123456'
host = '127.0.0.1'
db   = 'test'
 
data_file = 'mysql-test.dat'
 
create_table_sql = "CREATE TABLE IF NOT EXISTS mytable ( \
                    id int(10) AUTO_INCREMENT PRIMARY KEY, \
		    name varchar(20), age int(4) ) \
		    CHARACTER SET utf8"
 
insert_sql = "INSERT INTO mytable(name, age) VALUES ('Jay', 22 ), ('傑', 26)"
select_sql = "SELECT id, name, age FROM mytable"
 
cnx = mysql.connector.connect(user=user, password=pwd, host=host, database=db)
cursor = cnx.cursor()
 
try:
    cursor.execute(create_table_sql)
except mysql.connector.Error as err:
    print("create table 'mytable' failed.")
    print("Error: {}".format(err.msg))
    sys.exit()
 
try:
    cursor.execute(insert_sql)
except mysql.connector.Error as err:
    print("insert table 'mytable' failed.")
    print("Error: {}".format(err.msg))
    sys.exit()
 
if os.path.exists(data_file):
    myfile = open(data_file)
    lines = myfile.readlines()
    myfile.close()
 
    for line in lines:
        myset = line.split()
        sql = "INSERT INTO mytable (name, age) VALUES ('{}', {})".format(myset[0], myset[1])
        try:
            cursor.execute(sql)
        except mysql.connector.Error as err:
            print("insert table 'mytable' from file 'mysql-test.dat' -- failed.")
            print("Error: {}".format(err.msg))
            sys.exit()
 
try:
    cursor.execute(select_sql)
    for (id, name, age) in cursor:
        print("ID:{}  Name:{}  Age:{}".format(id, name, age))
except mysql.connector.Error as err:
    print("query table 'mytable' failed.")
    print("Error: {}".format(err.msg))
    sys.exit()
 
cnx.commit()
cursor.close()
cnx.close()

另外,最後再貼一個使用MySQLdb的python2.x代碼示例吧:python2.7

View Code PYTHON
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/python2.7
# coding=utf-8
 
import MySQLdb
import sys
 
host = 'localhost'
user = 'root'
pwd  = '123456'   # to be modified.
db   = 'test'
 
 
if __name__ == '__main__':
    conn = MySQLdb.connect(host, user, pwd, db, charset='utf8');
    try:
        conn.ping()
    except:
        print 'failed to connect MySQL.'
    sql = 'select * from mytable where id = 2'
    cur = conn.cursor()
    cur.execute(sql)
    row = cur.fetchone()
#    print type(row)
    for i in row:
        print i
    cur.close()
    conn.close()
    sys.exit()
相關文章
相關標籤/搜索