安裝
Python2
https://pypi.org/project/MySQL-python/pip install MySQL-python
Python3
https://pypi.org/project/mysqlclient/pip install mysqlclient
使用方式和PyMySQL 類似,如果有條件還是優先使用 PyMySQL :
可參考:
SQL:pymysql子產品讀寫mysql資料代碼示例
# -*- coding: utf-8 -*-
import MySQLdb
con_config = {
"host": "127.0.0.1",
"port": 3306,
"user": "root",
"password": "123456",
"database": "demo",
"autocommit": True # 不送出修改不生效,3中方式任選一種
}
# autocommit = True # 送出1:連接配接的時候就開啟自動送出
# con.autocommit(True) # 送出2:執行SQL語句之前設定自動送出
# con.commit() # 送出3:執行SQL語句之後送出
# 連接配接資料庫,獲得遊标
con = MySQLdb.connect(**con_config)
cursor = con.cursor()
# 1、插入單條資料
insert_sql = "insert into student(name, age) values(%s, %s)"
cursor.execute(insert_sql, ("Tom", 23))
print(cursor.rowcount)
# 1
# 2、插入多條資料
# 可用于改操作: insert, delete, update
cursor.executemany(insert_sql, [("Jack", 24), ("Jimi", 25)])
print(cursor.rowcount) # 無論送出還是不送出,rowcount都有資料,不要被誤導
# 2
# 3、删除資料
delete_sql = "delete from student where id=%s"
cursor.execute(delete_sql, (1,)) # 第二個參數為一個可疊代對象,隻有一個參數要傳元組
print(cursor.rowcount)
# 1
# 4、修改資料
update_sql = "update student set age=99 where id=%s"
cursor.execute(update_sql, (4,))
print(cursor.rowcount)
# 1
# 5、查詢單條 查詢不需要送出
select_sql = "select name, age from student limit %s"
cursor.execute(select_sql, (1,))
row = cursor.fetchone()
print(row)
# ('Tom', 99)
# 6、查詢多條資料
cursor.execute(select_sql, (2,))
rows = cursor.fetchall()
print(rows)
# (('Tom', 23), ('Tom', 23))
# 關閉遊标和資料庫連接配接
cursor.close()
con.close()