Table of contents
1 Introduction
This article will introduce how to connect to the mysql database through Python's pymysql library . You can visit my blog homepage to view other articles about python operating the MySQL database:
2. Code implementation
By default, you have already installed the pymysql library, and then write connect_to_database.py :
import pymysql
class ConnectToDatabase():
def __init__(self, hostname, username, password, database_name):
self.hostname = hostname # 主机名
self.username = username # 用户名
self.password = password # 密码
self.database_name = database_name # 数据库名称
# 连接数据库
def connect_to_database(self):
connection = pymysql.connect(
host=self.hostname,
user=self.username,
password=self.password,
database=self.database_name,
cursorclass=pymysql.cursors.DictCursor # 指定游标类型
)
return connection
Here I write the method of connecting to the database into the ConnectToDatabase class in order to improve the reusability and readability of the code.
3. Test code
(1) Write test code
Write the test code connect_to_database.py :
import pymysql
from main.connect_to_database import ConnectToDatabase
if __name__ == '__main__':
try:
connection = ConnectToDatabase('主机名', '用户名', '密码', '数据库名').connect_to_database()
print('数据库连接成功')
# 关闭数据库连接
connection.close()
except pymysql.Error as e:
print(f'数据库连接失败,{e}')
(2) Run the test code
Be careful to replace the information connecting to the database in the test code with your own! Also pay attention to the directory structure in case the module cannot be referenced.
4. Summary
So far we have completed the operation of using pymysql to connect to the mysql database. The follow-up article will continue to introduce the further operation of the mysql database using the pymysql library. If you have any questions about the above content, you can discuss it in the comment area or private message me