写一个代码 python操作mysql创建表并增删改查的类
时间: 2023-09-11 11:05:09 浏览: 236
### 回答1:
import pymysql # 引入 MySQLdb 模块class MysqlDatabase:
# 定义数据库操作类
def __init__(self):
# 初始化数据库连接
self.db = pymysql.connect("localhost", "root", "123456", "db_name")
self.cursor = self.db.cursor() def createTable(self, sql):
# 创建表
try:
self.cursor.execute(sql)
self.db.commit()
except:
self.db.rollback() def insertData(self, sql, params):
# 插入数据
try:
self.cursor.execute(sql, params)
self.db.commit()
except:
self.db.rollback() def deleteData(self, sql):
# 删除数据
try:
self.cursor.execute(sql)
self.db.commit()
except:
self.db.rollback() def updateData(self, sql):
# 更新数据
try:
self.cursor.execute(sql)
self.db.commit()
except:
self.db.rollback() def queryData(self, sql):
# 查询数据
try:
self.cursor.execute(sql)
data = self.cursor.fetchall()
return data
except:
self.db.rollback() def __del__(self):
# 关闭数据库连接
self.db.close()我可以回答你的问题吗?
### 回答2:
下面是一个示例的 Python 代码,用于操作 MySQL 创建表并进行增删改查的类。
```python
import mysql.connector
class MySQLHandler:
def __init__(self, host, user, password, database):
self.connection = mysql.connector.connect(
host=host,
user=user,
password=password,
database=database
)
self.cursor = self.connection.cursor()
def create_table(self, table_name, columns):
create_table_query = f"CREATE TABLE IF NOT EXISTS {table_name} ({columns})"
self.cursor.execute(create_table_query)
self.connection.commit()
print(f"Table {table_name} created successfully.")
def insert_data(self, table_name, data):
columns = ", ".join(data.keys())
values = ", ".join(["%s"] * len(data.values()))
insert_data_query = f"INSERT INTO {table_name} ({columns}) VALUES ({values})"
self.cursor.execute(insert_data_query, list(data.values()))
self.connection.commit()
print("Data inserted successfully.")
def update_data(self, table_name, data, condition):
columns = ", ".join([f"{key} = %s" for key in data.keys()])
update_data_query = f"UPDATE {table_name} SET {columns} WHERE {condition}"
self.cursor.execute(update_data_query, list(data.values()))
self.connection.commit()
print("Data updated successfully.")
def delete_data(self, table_name, condition):
delete_data_query = f"DELETE FROM {table_name} WHERE {condition}"
self.cursor.execute(delete_data_query)
self.connection.commit()
print("Data deleted successfully.")
def select_data(self, table_name, condition=""):
select_data_query = f"SELECT * FROM {table_name}"
if condition != "":
select_data_query += f" WHERE {condition}"
self.cursor.execute(select_data_query)
result = self.cursor.fetchall()
print("Selected data:")
for row in result:
print(row)
def close_connection(self):
self.cursor.close()
self.connection.close()
print("Connection closed.")
# 使用示例:
handler = MySQLHandler("localhost", "root", "password", "example_db")
handler.create_table("students", "id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), age INT")
handler.insert_data("students", {"name": "John", "age": 25})
handler.update_data("students", {"age": 30}, "name = 'John'")
handler.delete_data("students", "name = 'John'")
handler.select_data("students")
handler.close_connection()
```
以上代码提供了一个 MySQLHandler 类,可以连接到 MySQL 数据库,创建表,插入、更新、删除和查询数据。可以根据实际需求进行相应的调用。
### 回答3:
下面是一个简单的Python代码,可以用来操作MySQL数据库创建表并进行增删改查。
```python
import mysql.connector
class MySQLDB:
def __init__(self, host, username, password, database):
self.conn = mysql.connector.connect(
host=host,
user=username,
password=password,
database=database
)
self.cursor = self.conn.cursor()
def create_table(self, table_name, columns):
query = f"CREATE TABLE {table_name} ({columns})"
self.cursor.execute(query)
self.conn.commit()
print(f"Table '{table_name}' created successfully.")
def insert_data(self, table_name, data):
keys = ", ".join(data.keys())
values = ", ".join(["%s"] * len(data.values()))
query = f"INSERT INTO {table_name} ({keys}) VALUES ({values})"
self.cursor.execute(query, tuple(data.values()))
self.conn.commit()
print("Data inserted successfully.")
def update_data(self, table_name, data, condition=None):
values = ", ".join([f"{key} = %s" for key in data.keys()])
query = f"UPDATE {table_name} SET {values}"
if condition:
query += f" WHERE {condition}"
self.cursor.execute(query, tuple(data.values()))
self.conn.commit()
print("Data updated successfully.")
def delete_data(self, table_name, condition=None):
query = f"DELETE FROM {table_name}"
if condition:
query += f" WHERE {condition}"
self.cursor.execute(query)
self.conn.commit()
print("Data deleted successfully.")
def select_data(self, table_name, columns="*", condition=None):
query = f"SELECT {columns} FROM {table_name}"
if condition:
query += f" WHERE {condition}"
self.cursor.execute(query)
result = self.cursor.fetchall()
return result
# 示例用法
db = MySQLDB(host="localhost", username="root", password="password", database="test_db")
# 创建表
db.create_table("students", "id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT")
# 插入数据
data = {"name": "John", "age": 20}
db.insert_data("students", data)
# 更新数据
data = {"name": "Jane"}
db.update_data("students", data, "id = 1")
# 删除数据
db.delete_data("students", "id = 1")
# 查询数据
result = db.select_data("students")
print(result)
```
这个类封装了常用的MySQL数据库操作,包括创建表、插入数据、更新数据、删除数据和查询数据。你可以根据具体的需求修改表名、字段和数据,或者增加其他需要的方法。请确保已经安装了`mysql-connector-python`库,可以使用以下命令进行安装:
```
pip install mysql-connector-python
```
阅读全文