#python demo code for MySQL drive
#使用 pymysql 套件
import pymysql
#############################################################
class Database:
def __init__(self, host, user, password, database, charset='utf8mb4'):
self.conn = pymysql.connect(
host=host,
user=user,
password=password,
database=database,
charset=charset
)
self.cursor = self.conn.cursor()
def insert(self, table, data):
# Build the INSERT statement
columns = ', '.join(data.keys())
values = ', '.join("'" + str(value) + "'" for value in data.values())
sql = f"INSERT INTO {table} ({columns}) VALUES ({values})"
# Execute the INSERT statement
self.cursor.execute(sql)
self.conn.commit()
def select(self, table, conditions=None):
# Build the SELECT statement
sql = f"SELECT * FROM {table}"
if conditions:
sql += " WHERE " + " AND ".join([f"{key}='{value}'" for key, value in conditions.items()])
# Execute the SELECT statement
self.cursor.execute(sql)
rows = self.cursor.fetchall()
return rows
def update(self, table, data, conditions):
# Build the UPDATE statement
set_values = ', '.join([f"{key}='{value}'" for key, value in data.items()])
where_conditions = " AND ".join([f"{key}='{value}'" for key, value in conditions.items()])
sql = f"UPDATE {table} SET {set_values} WHERE {where_conditions}"
# Execute the UPDATE statement
self.cursor.execute(sql)
self.conn.commit()
def delete(self, table, conditions):
# Build the DELETE statement
where_conditions = " AND ".join([f"{key}='{value}'" for key, value in conditions.items()])
sql = f"DELETE FROM {table} WHERE {where_conditions}"
# Execute the DELETE statement
self.cursor.execute(sql)
self.conn.commit()
def close(self):
self.cursor.close()
self.conn.close()
########################################################
python class 使用範例
# Create an instance of the Database class
db = Database(host='hostname', user='username', password='password', database='database_name')
# Insert data into the database
data = {
'column1': 'value1',
'column2': 'value2',
'column3': 'value3'
}
db.insert('table_name', data)
# Select data from the database
rows = db.select('table_name')
for row in rows:
print(row)
# Update data in the database
data = {
'column2':
沒有留言:
張貼留言