2015年11月24日 星期二

[Python] 在Ubuntu 14.04,使用Python撰寫MySql程式


  • 安裝Python 套件
  • #apt-get install python-mysqldb

  • Sample Code
  • import MySQLdb

    try :
        db = MySQLdb.connect("host", "username", "password", "db_name", charset='utf-8')

        sql = "SELECT field1, field2 FROM table"
        cursor = db.cursor()
        cursor.execute(sql)

        results = cursor.fetchall()
        for record in results:
           col1 = record[0]
           col2 = record[1]
           print "%s, %s" % (col1, col2)

        db.close()
    except MySQLdb.Error as e:
        print "Error %d: %s" % (e.args[0], e.args[1])

Reference :
[1] 實作Python 連接MySQL 資料庫

沒有留言:

張貼留言