python连接mysql数据库 类
时间: 2024-01-16 17:18:00 浏览: 101
一个mysql数据库连接类
以下是一个简单的Python类,用于连接MySQL数据库:
```python
import pymysql
class MySQLConnector:
def __init__(self, host, user, password, database):
self.host = host
self.user = user
self.password = password
self.database = database
self.connection = None
def connect(self):
try:
self.connection = pymysql.connect(
host=self.host,
user=self.user,
password=self.password,
database=self.database
)
print("Connected to MySQL database!")
except pymysql.Error as e:
print(f"Error connecting to MySQL database: {e}")
def disconnect(self):
if self.connection:
self.connection.close()
print("Disconnected from MySQL database!")
def execute_query(self, query):
if self.connection:
try:
with self.connection.cursor() as cursor:
cursor.execute(query)
result = cursor.fetchall()
return result
except pymysql.Error as e:
print(f"Error executing query: {e}")
else:
print("Not connected to MySQL database!")
# 示例用法
connector = MySQLConnector("localhost", "root", "password", "mydatabase")
connector.connect()
# 执行查询
result = connector.execute_query("SELECT * FROM mytable")
print(result)
# 断开连接
connector.disconnect()
```
阅读全文