pyqt5 连接mysql数据库 并指定端口
时间: 2023-08-16 14:06:40 浏览: 207
要在PyQt5中连接MySQL数据库并指定端口,您需要使用Python的MySQL连接器。以下是一个示例代码,它将连接到MySQL数据库localhost上的端口3306:
```python
import pymysql
from PyQt5.QtSql import QSqlDatabase
# Connect to MySQL database
db = pymysql.connect(host='localhost', port=3306, user='your_username', passwd='your_password', db='your_database')
# Check if the connection is successful
if db:
print("Connection successful")
# Set up a QSqlDatabase object with the connection
database = QSqlDatabase.addDatabase("QMYSQL")
database.setHostName("localhost")
database.setPort(3306)
database.setUserName("your_username")
database.setPassword("your_password")
database.setDatabaseName("your_database")
# Open the connection
if database.open():
print("Database connection established")
else:
print("Failed to connect to database")
```
请注意,您需要将“your_username”、“your_password”和“your_database”替换为实际的MySQL用户名、密码和数据库名称。
阅读全文