準備工作 :
安裝 pymysql
- 命令:pip install pymysql
重要函數
函數 | 說明 |
connect | 創建鏈接 |
cursor | 創建一個遊標 |
commit | 事務提交,如果沒有設爲自動提交,則每次操作後必須提交事務,否則操作無效。 |
rollback | 操作出錯時,可以用這個函數回滾到執行事務之前 |
close | 關閉連接 |
創建鏈接:
conn = pymysql.connect(host="localhost",
db="test",
user="root",
password="",
port=3306,
charset="utf8"
)
向數據庫中添加一條信息:
cursor = conn.cursor()
sql_insert = "INSERT INTO book(name,price) VALUES ('hhh', 7)"
try:
cursor.execute(sql_insert)
conn.commit()
except Exception as e:
conn.rollback()
conn.close()
表結構如下:
connect參數:
self,
host=None, # 要連接的主機地址
user=None, # 用於登錄的數據庫用戶
password='', # 密碼
database=None, # 要連接的數據庫
port=0, # 端口,一般爲 3306
unix_socket=None, # 選擇是否要用unix_socket而不是TCP/IP
charset='', # 字符編碼
sql_mode=None, # Default SQL_MODE to use.
read_default_file=None, # 從默認配置文件(my.ini或my.cnf)中讀取參數
conv=None, # 轉換字典
use_unicode=None, # 是否使用 unicode 編碼
client_flag=0, # Custom flags to send to MySQL. Find potential values in constants.CLIENT.
cursorclass=<class 'pymysql.cursors.Cursor'>, # 選擇 Cursor 類型
init_command=None, # 連接建立時運行的初始語句
connect_timeout=10, # 連接超時時間,(default: 10, min: 1, max: 31536000)
ssl=None, # A dict of arguments similar to mysql_ssl_set()'s parameters.For now the capath and cipher arguments are not supported.
read_default_group=None, # Group to read from in the configuration file.
compress=None, # 不支持
named_pipe=None, # 不支持
no_delay=None, #
autocommit=False, # 是否自動提交事務
db=None, # 同 database,爲了兼容 MySQLdb
passwd=None, # 同 password,爲了兼容 MySQLdb
local_infile=False, # 是否允許載入本地文件
max_allowed_packet=16777216, # 限制 `LOCAL DATA INFILE` 大小
defer_connect=False, # Don't explicitly connect on contruction - wait for connect call.
auth_plugin_map={}, #
read_timeout=None, #
write_timeout=None,
bind_address=None # 當客戶有多個網絡接口,指定一個連接到主機
完整代碼:
import pymysql
def getConnection():
conn = pymysql.connect(host="localhost",
db="test",
user="root",
password="",
port=3306,
charset="utf8"
)
return conn
def Insert():
conn = getConnection()
cursor = conn.cursor()
sql_insert = "INSERT INTO book(name,price) VALUES ('hhh', 7)"
try:
cursor.execute(sql_insert)
conn.commit()
except Exception as e:
conn.rollback()
conn.close()
def Delete():
conn = getConnection()
cursor = conn.cursor()
sql_delete = "DELETE FROM book WHERE NAME = %s"
try:
cursor.execute(sql_delete, ("hhh", ))
conn.commit()
except Exception as e:
conn.rollback()
conn.close()
def Update():
coon = getConnection()
cursor = coon.cursor()
update_delete = "UPDATE book SET NAME = %s WHERE NAME = 'test2'"
try:
cursor.execute(update_delete, ("update",))
coon.commit()
except Exception as e:
coon.rollback()
coon.close()
def Select():
coon = getConnection()
cursor = coon.cursor()
sql = "SELECT * FROM book WHERE name = %s"
try:
count = cursor.execute(sql, ("TEST",))
except Exception as e:
coon.rollback()
print(count)
#Insert()
#Select()
#Delete()
Update()