使用python封装一个mysql类
时间: 2023-05-15 07:04:57 浏览: 86
好的,以下是一个简单的Python封装MySQL类的示例代码:
```python
import mysql.connector
class MySQL:
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)
result = self.cursor.fetchall()
return result
def execute_update(self, query):
self.cursor.execute(query)
self.connection.commit()
```
你可以使用这个类来执行查询和更新操作,例如:
```python
db = MySQL('localhost', 'root', 'password', 'mydatabase')
result = db.execute_query('SELECT * FROM mytable')
db.execute_update('UPDATE mytable SET column1 = "new value" WHERE id = 1')
```
希望这个示例对你有所帮助!