Python3串連MySQL

來源:互聯網
上載者:User

標籤:abs   null   charset   列印   介紹   mysql   一個   異常   div   

Python3串連MySQL

本文介紹Python3串連MySQL的第三方庫--PyMySQL的基本使用。

PyMySQL介紹

PyMySQL 是在 Python3.x 版本中用於串連 MySQL 伺服器的一個庫,Python2中則使用mysqldb。

Django中也可以使用PyMySQL串連MySQL資料庫。

PyMySQL安裝
pip install pymysql
串連資料庫注意事項

在進行本文以下內容之前需要注意:

  • 你有一個MySQL資料庫,並且已經啟動。
  • 你有可以串連該資料庫的使用者名稱和密碼
  • 你有一個有許可權操作的database
基本使用
# 匯入pymysql模組import pymysql# 串連databaseconn = pymysql.connect(host=“你的資料庫地址”, user=“使用者名稱”,password=“密碼”,database=“資料庫名”,charset=“utf8”)# 得到一個可以執行SQL語句的游標對象cursor = conn.cursor()# 定義要執行的SQL語句sql = """CREATE TABLE USER1 (id INT auto_increment PRIMARY KEY ,name CHAR(10) NOT NULL UNIQUE,age TINYINT NOT NULL)ENGINE=innodb DEFAULT CHARSET=utf8;"""# 執行SQL語句cursor.execute(sql)# 關閉游標對象cursor.close()# 關閉資料庫連接conn.close()

返回字典格式資料:

# 匯入pymysql模組import pymysql# 串連databaseconn = pymysql.connect(host=“你的資料庫地址”, user=“使用者名稱”,password=“密碼”,database=“資料庫名”,charset=“utf8”)# 得到一個可以執行SQL語句並且將結果作為字典返回的遊標cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)# 定義要執行的SQL語句sql = """CREATE TABLE USER1 (id INT auto_increment PRIMARY KEY ,name CHAR(10) NOT NULL UNIQUE,age TINYINT NOT NULL)ENGINE=innodb DEFAULT CHARSET=utf8;"""# 執行SQL語句cursor.execute(sql)# 關閉游標對象cursor.close()# 關閉資料庫連接conn.close()

注意:

charset=“utf8”,編碼不要寫成"utf-8"

增刪改查操作增
# 匯入pymysql模組import pymysql# 串連databaseconn = pymysql.connect(host=“你的資料庫地址”, user=“使用者名稱”,password=“密碼”,database=“資料庫名”,charset=“utf8”)# 得到一個可以執行SQL語句的游標對象cursor = conn.cursor()sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"username = "Alex"age = 18# 執行SQL語句cursor.execute(sql, [username, age])# 提交事務conn.commit()cursor.close()conn.close()

插入資料失敗復原

# 匯入pymysql模組import pymysql# 串連databaseconn = pymysql.connect(host=“你的資料庫地址”, user=“使用者名稱”,password=“密碼”,database=“資料庫名”,charset=“utf8”)# 得到一個可以執行SQL語句的游標對象cursor = conn.cursor()sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"username = "Alex"age = 18try:    # 執行SQL語句    cursor.execute(sql, [username, age])    # 提交事務    conn.commit()except Exception as e:    # 有異常,復原事務    conn.rollback()cursor.close()conn.close()

擷取插入資料的ID(關聯操作時會用到)

# 匯入pymysql模組import pymysql# 串連databaseconn = pymysql.connect(host=“你的資料庫地址”, user=“使用者名稱”,password=“密碼”,database=“資料庫名”,charset=“utf8”)# 得到一個可以執行SQL語句的游標對象cursor = conn.cursor()sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"username = "Alex"age = 18try:    # 執行SQL語句    cursor.execute(sql, [username, age])    # 提交事務    conn.commit()    # 提交之後,擷取剛插入的資料的ID    last_id = cursor.lastrowidexcept Exception as e:    # 有異常,復原事務    conn.rollback()cursor.close()conn.close()

批量執行

# 匯入pymysql模組import pymysql# 串連databaseconn = pymysql.connect(host=“你的資料庫地址”, user=“使用者名稱”,password=“密碼”,database=“資料庫名”,charset=“utf8”)# 得到一個可以執行SQL語句的游標對象cursor = conn.cursor()sql = "INSERT INTO USER1(name, age) VALUES (%s, %s);"data = [("Alex", 18), ("Egon", 20), ("Yuan", 21)]try:    # 批量執行多條插入SQL語句    cursor.executemany(sql, data)    # 提交事務    conn.commit()except Exception as e:    # 有異常,復原事務    conn.rollback()cursor.close()conn.close()
# 匯入pymysql模組import pymysql# 串連databaseconn = pymysql.connect(host=“你的資料庫地址”, user=“使用者名稱”,password=“密碼”,database=“資料庫名”,charset=“utf8”)# 得到一個可以執行SQL語句的游標對象cursor = conn.cursor()sql = "DELETE FROM USER1 WHERE id=%s;"try:    cursor.execute(sql, [4])    # 提交事務    conn.commit()except Exception as e:    # 有異常,復原事務    conn.rollback()cursor.close()conn.close()
# 匯入pymysql模組import pymysql# 串連databaseconn = pymysql.connect(host=“你的資料庫地址”, user=“使用者名稱”,password=“密碼”,database=“資料庫名”,charset=“utf8”)# 得到一個可以執行SQL語句的游標對象cursor = conn.cursor()# 修改資料的SQL語句sql = "UPDATE USER1 SET age=%s WHERE name=%s;"username = "Alex"age = 80try:    # 執行SQL語句    cursor.execute(sql, [age, username])    # 提交事務    conn.commit()except Exception as e:    # 有異常,復原事務    conn.rollback()cursor.close()conn.close()

 

查詢單條資料

# 匯入pymysql模組import pymysql# 串連databaseconn = pymysql.connect(host=“你的資料庫地址”, user=“使用者名稱”,password=“密碼”,database=“資料庫名”,charset=“utf8”)# 得到一個可以執行SQL語句的游標對象cursor = conn.cursor()# 查詢資料的SQL語句sql = "SELECT id,name,age from USER1 WHERE id=1;"# 執行SQL語句cursor.execute(sql)# 擷取單條查詢資料ret = cursor.fetchone()cursor.close()conn.close()# 列印下查詢結果print(ret)

查詢多條資料

# 匯入pymysql模組import pymysql# 串連databaseconn = pymysql.connect(host=“你的資料庫地址”, user=“使用者名稱”,password=“密碼”,database=“資料庫名”,charset=“utf8”)# 得到一個可以執行SQL語句的游標對象cursor = conn.cursor()# 查詢資料的SQL語句sql = "SELECT id,name,age from USER1;"# 執行SQL語句cursor.execute(sql)# 擷取多條查詢資料ret = cursor.fetchall()cursor.close()conn.close()# 列印下查詢結果print(ret)
 進階用法
# 可以擷取指定數量的資料cursor.fetchmany(3)# 游標按絕對位置移動1cursor.scroll(1, mode="absolute")# 游標按照相對位置(當前位置)移動1cursor.scroll(1, mode="relative")

Python3串連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.