Python操作MySQL資料庫

來源:互聯網
上載者:User

標籤:

參考:http://www.w3cschool.cc/python/python-mysql.html

假定:

  • 已經安裝好MySQL並建立了資料庫 TESTDB
  • 串連資料庫TESTDB使用的使用者名稱為 "testuser" ,密碼為 "test123"
  • 在你的機子上已經安裝了 Python MySQLdb 模組

Python操作MySQL建立表示例:

 1 # encoding: utf-8 2 #!/usr/bin/python 3  4 import MySQLdb 5  6 # 開啟資料庫連接 7 db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) 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()

向表中寫入資料樣本:

 1 # encoding: utf-8 2 #!/usr/bin/python 3  4 import MySQLdb 5  6 # 開啟資料庫連接 7 db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) 8  9 # 使用cursor()方法擷取操作遊標 10 cursor = db.cursor()11 12 # SQL 插入語句13 sql = """INSERT INTO EMPLOYEE(FIRST_NAME,14          LAST_NAME, AGE, SEX, INCOME)15          VALUES (‘Mac‘, ‘Mohan‘, 20, ‘M‘, 2000)"""16 try:17    # 執行sql語句18    cursor.execute(sql)19    # 提交到資料庫執行20    db.commit()21 except:22    # Rollback in case there is any error23    db.rollback()24 25 # 關閉資料庫連接26 db.close()

查詢樣本:

 1 # encoding: utf-8 2 #!/usr/bin/python 3  4 import MySQLdb 5  6 # 開啟資料庫連接 7 db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) 8  9 # 使用cursor()方法擷取操作遊標 10 cursor = db.cursor()11 12 # SQL 查詢語句13 sql = "SELECT * FROM EMPLOYEE 14        WHERE INCOME > ‘%d‘" % (1000)15 try:16    # 執行SQL語句17    cursor.execute(sql)18    # 擷取所有記錄列表19    results = cursor.fetchall()20    for row in results:21       fname = row[0]22       lname = row[1]23       age = row[2]24       sex = row[3]25       income = row[4]26       # 列印結果27       print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % 28              (fname, lname, age, sex, income )29 except:30    print "Error: unable to fecth data"31 32 # 關閉資料庫連接33 db.close()

事務樣本:

 1 # SQL刪除記錄語句 2 sql = "DELETE FROM EMPLOYEE WHERE AGE > ‘%d‘" % (20) 3 try: 4    # 執行SQL語句 5    cursor.execute(sql) 6    # 向資料庫提交 7    db.commit() 8 except: 9    # 發生錯誤時復原10    db.rollback()

Python操作MySQL資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.