Python3連結MySQL資料庫

來源:互聯網
上載者:User

標籤:http   使用   os   io   檔案   資料   for   ar   

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 
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
#!/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.connectorimport 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 
12345678910111213141516171819202122232425262728
#!/usr/bin/python2.7# coding=utf-8 import MySQLdbimport 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()
 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.