Python 2.x 上连接MySQL的库倒是不少的,其中比较著名就是MySQLdb(Django项目都使用它;我也在开发测试系统时也使用过),见:http://sourceforge.net/projects/mysql-python/

不过,目前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/目录下的文件过去就解决。)

另外,Python3.x连接MySQL的其他方案有:oursql, PyMySQL, myconnpy 等,参考如下链接:

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

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

https://launchpad.net/myconnpy

下面只是贴一个试用 MySQL Connector/Python 的Python脚本吧(包括创建表、插入数据、从文件读取并插入数据、查询数据等):

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代码示例吧:

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()
 
标签: MySQLPython
 
    1. VerSun
      三 12th, 201306:59
      回复 | 引用 | #1
       

      最近正要开始学MySQL呢。。

       
    2. bigtan
      十二 6th, 201308:52
      回复 | 引用 | #2
       

      这个太有帮助了,感谢博主。另外64位在安装会有一些小的bug,不过已经解决了

       
    3. by
      十二 14th, 201319:56
      回复 | 引用 | #3
       

      请问一下,MySQLdb库与这个MySQL Connnector有什么差别么?网上关于MySQL Connnector实在是太少,但是有很多MySQLdb,不知道可不可以直接拿来用呢?

       
      • master
        十二 15th, 201317:28
        回复 | 引用 | #4
         

        二者功能差不多的~ 只是MySQLdb暂不支持python3;如果是python2,你选那个库都无所。 另外,MySQL Connector的文官方文档很好了啊,博客中我也提到了。

         
    4. by
      十二 17th, 201322:15
      回复 | 引用 | #5
       

      好的,多谢了。。。
      主要我之前没有任何的编程经验,直接看那个API还是有很多不理解的地方。。。

       
    5. by
      十二 28th, 201305:28
      回复 | 引用 | #6
       

      你好,我现在还有一个问题想请教一下。
      我现在要往一个稀疏的table里面插值,因为插插入到哪一行和哪一列都不确定,所以需要用%s代替列的名称,我的代码是:
      cur.execute(“UPDATE myTABLE SET %s=%s WHERE model_id=%s”, (‘Depth’,‘17cm’, 001))
      不过似乎MySQLConnector API不支持列名的替换,所以会有syntax error,如果我用
      cur.executemany(“UPDATE myTABLE SET Depth=%s WHERE model_id=%s”, (’17cm‘, 001))
      就不会报错。
      有没有办法解决这个问题呢?

       
      • master
        十二 28th, 201306:27
        回复 | 引用 | #7
         

        应该不会出现你说的情况,你可以这样来做:
        sql = “UPDATE myTABLE SET %s=%s WHERE model_id=%s” % (‘Depth’, ’17cm’, ’001′) #第一次,我写错了,现在改了
        print sql #打印出来看看Sql正确吗
        cur.execute(sql)

         
    6. by
      十二 28th, 201305:29
      回复 | 引用 | #8
       

      多谢啦

       
    7. by
      十二 28th, 201305:30
      回复 | 引用 | #9
       

      更正一下,我最后一行的代码应该是
      cur.execute(“UPDATE myTABLE SET Depth=%s WHERE model_id=%s”, (’17cm’, 001))

       
    8. by
      一 1st, 201402:32
      回复 | 引用 | #10
       

      还是不行。我用了你的方法,报的错误是:AttributeError: ‘tuple’ object has no attribute ‘encode’
      我试了另外一种:cur.execute(“UPDATE myTABLE SET %s=%s WHERE model_id=%s” %(‘Depth’, ’17cm’, ’001′))
      会报错:mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column ’17cm’ in ‘field list’。
      如果把17cm换成17就没有问题。

      不好意思,我Python和mysql都是刚接触,很多error不知道什么意思。。

       
      • master
        一 1st, 201410:31
        回复 | 引用 | #11
         

        不好意思,我那个例子抄你上面写的,也是写错的,应该是:
        sql = “UPDATE myTABLE SET %s=%s WHERE model_id=%s” % (‘Depth’, ’17cm’, ’001′)

         
    9. by
      一 1st, 201402:34
      回复 | 引用 | #12
       

      其实我真正要做的是事情是用executemany来多次update table,但是目前似乎只update一次就搞不定。。。是因为对column name进行替换的原因么?

       
    10. by
      一 1st, 201402:37
      回复 | 引用 | #13
       

      如果我用executemany的话:
      cur.executemany(“UPDATE myTABLE SET %s=%s WHERE id=%s” % data)
      data=[('Depth', '17.5cm', Decimal('002')), ('Input_Voltage', '110 V AC', Decimal('001'))]
      会有如下错误:TypeError: not enough arguments for format string
      圣诞期间一直再搞这个,就是搞不定。。。

       
    11. 依赖
      一 4th, 201414:00
      回复 | 引用 | #14
       

      你好,请教你一个问题:
      我目前用得是PyCharm MySQL5.5 Python3.3 mac系统 MySQL Connnector django库 这些都装完之后,
      运行:
      import mysql.connector
      import django
      import sys
      print (django.get_version())

      print (sys.version_info)

      出现:ImportError: No module named ‘mysql’ 找不到mysql库,不知道是什么原因导致的,而且我的MySQL Connnector确定装上了;楼主遇到过么????怎么解决呢????

       
    12. by
      一 5th, 201408:12
      回复 | 引用 | #16
       

      最后我将数据全导入到python里面,然后在python里面改的。。。不管怎么样,非常感谢耐心解答啊!

       
      • master
        一 7th, 201416:54
        回复 | 引用 | #17
         

        不用谢,相互讨论和学习~~

 posted on 2014-11-04 12:17  大雄fcl  阅读(621)  评论(0编辑  收藏  举报