PyMySQL模塊
Python—連接mysql數(shù)據(jù)庫(kù)代碼。文章來源:http://www.zghlxwxcb.cn/news/detail-564924.html
- 原理圖
from pymysql import connect, Error
class Mysql:
"""初始化Mysql數(shù)據(jù)庫(kù)"""
def __init__(self, hostname, port, username, password):
self.hostname = hostname
self.port = port
self.username = username
self.password = password
"""創(chuàng)建數(shù)據(jù)庫(kù)連接對(duì)象"""
def conn_db(self):
try:
conn = connect(host=self.hostname, port=self.port, user=self.username, password=self.password)
return conn
except Error as e:
print(e)
"""執(zhí)行SQL語(yǔ)句"""
def exec_sql(self, sql):
connection = None
try:
connection = self.conn_db()
with connection.cursor() as cursor:
cursor.execute(create_database) # 沒有數(shù)據(jù)庫(kù),第一次需要?jiǎng)?chuàng)建。
cursor.execute(choice_database) # 選擇數(shù)據(jù)庫(kù)
cursor.execute(sql) # 執(zhí)行SQL語(yǔ)句
if 'CREATE' in sql or 'INSERT' in sql or 'UPDATE' in sql or 'DELETE' in sql or 'DROP' in sql:
connection.commit()
print("數(shù)據(jù)操作成功!")
elif 'SHOW' in sql or 'SELECT' in sql:
result = cursor.fetchall()
print(f"result:{result}")
print("數(shù)據(jù)庫(kù)讀取成功!")
except Error as e:
print(e)
finally:
# 關(guān)閉游標(biāo)
cursor.close()
# 關(guān)閉連接
connection.close()
if __name__ == '__main__':
open_sql = Mysql(hostname='127.0.0.1', port=3306, username='root', password='123456')
open_sql.exec_sql(update_users) # 單個(gè)SQL語(yǔ)句的執(zhí)行
sqls = [create_users_table, insert_users, update_users, delete_user, drop_table, drop_database] # 多個(gè)SQL語(yǔ)句執(zhí)行
for sql in sqls:
open_sql.exec_sql(sql)
標(biāo)準(zhǔn)化數(shù)據(jù)庫(kù)連接格式(后續(xù)會(huì)持續(xù)更新)文章來源地址http://www.zghlxwxcb.cn/news/detail-564924.html
# 創(chuàng)建數(shù)據(jù)庫(kù)
create_database = """
CREATE DATABASE IF NOT EXISTS students
"""
# 選擇數(shù)據(jù)庫(kù)
choice_database = """
use students
"""
# 建表
create_users_table = """
CREATE TABLE IF NOT EXISTS users(
id INT AUTO_INCREMENT,
name TEXT NOT NULL,
age INT,
gender TEXT,
PRIMARY KEY (id)
)
"""
# 插入記錄,注意:`users`, `name`, `age`, `gender`,不是引號(hào)包裹,是鍵盤左上角的撇號(hào)
insert_users = """
INSERT INTO
`users` (`name`, `age`, `gender`)
VALUES
('zhangsan',23,'male'),
('lisi',24,'female'),
('wangwu',25,'male');
"""
# 更改
update_users = """
UPDATE `users` set `name`='jack' where `name` = 'zhangsan'
"""
# 查詢
select_users = "SELECT * FROM users"
# 刪除記錄
delete_user = """
DELETE from users where `name`="lisi"
"""
# 刪除表
drop_table = "DROP table users"
# 刪除數(shù)據(jù)庫(kù)
drop_database = "DROP database students"
到了這里,關(guān)于Python模塊—PyMySQL模塊的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!