Mysql 增删改查 写一个类
作者:互联网
### MySQL增删改查类
```python
import mysql.connector
class MySQLHandler:
def __init__(self, host, user, password, database):
self.host = host
self.user = user
self.password = password
self.database = database
self.connection = mysql.connector.connect(
host=self.host,
user=self.user,
password=self.password,
database=self.database
)
self.cursor = self.connection.cursor()
def execute_query(self, query):
self.cursor.execute(query)
self.connection.commit()
return self.cursor.fetchall()
def select(self, table, conditions=None):
query = f"SELECT * FROM {table}"
if conditions:
query += f" WHERE {conditions}"
return self.execute_query(query)
def insert(self, table, values):
query = f"INSERT INTO {table} VALUES {values}"
self.execute_query(query)
def update(self, table, new_values, conditions=None):
set_values = ','.join([f'{key}={value}' for key, value in new_values.items()])
query = f"UPDATE {table} SET {set_values}"
if conditions:
query += f" WHERE {conditions}"
self.execute_query(query)
def delete(self, table, conditions=None):
query = f"DELETE FROM {table}"
if conditions:
query += f" WHERE {conditions}"
self.execute_query(query)
def close_connection(self):
self.cursor.close()
self.connection.close()
# Example Usage:
handler = MySQLHandler("localhost", "root", "password", "mydatabase")
result = handler.select("users", "age > 18")
print(result)
handler.insert("users", "('Alice', 25)")
handler.update("users", {"age": 26}, "name = 'Alice'")
handler.delete("users", "name = 'Alice'")
handler.close_connection()
Markdown
This is a simple Python class for handling MySQL queries. It includes methods for selecting, inserting, updating, and deleting data from a given table. You can instantiate an object of this class with the necessary connection details and then perform database operations using the defined methods. The class utilizes the `mysql.connector` module for connecting to the MySQL database. You can see an example usage of this class at the bottom of the code snippet.
标签: 来源: