给出数据库连接的封装类,实现连接数据库、执行sql命令的函数
时间: 2024-06-10 17:07:41 浏览: 113
为您提供以下示例代码,供参考:
```python
import pymysql
class DBHandler():
def __init__(self, host, port, user, password, database):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self.conn = self.connect_db()
self.cursor = self.conn.cursor()
def __del__(self):
self.cursor.close()
self.conn.close()
def connect_db(self):
conn = pymysql.connect(host=self.host, port=self.port, user=self.user,
password=self.password, database=self.database, charset='utf8')
return conn
def execute_sql(self, sql_query: str):
try:
self.cursor.execute(sql_query)
self.conn.commit()
return self.cursor.fetchall()
except:
self.conn.rollback()
if __name__ == '__main__':
db = DBHandler('localhost', '3306', 'root', 'password', 'test_db')
data = db.execute_sql("select * from user_info")
print(data)
```
以上示例使用Python的pymysql库,实现了数据库连接及执行sql命令的功能。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)