tomact与mysql连接代码
时间: 2024-04-29 17:23:21 浏览: 6
以下是使用Python中的tomact连接MySQL的示例代码:
```
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='mydatabase',
user='myusername',
password='mypassword')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL database... MySQL Server version on",db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("Your connected to - ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
```
在上面的代码中,我们使用`mysql.connector`模块来连接MySQL数据库。我们提供了MySQL数据库的主机地址、数据库名称、用户名和密码来连接数据库。如果连接成功,我们可以执行MySQL查询并获得查询结果。最后,我们关闭了数据库连接。
请注意,您需要安装`mysql-connector-python`模块来执行此代码。您可以使用以下命令在命令行中安装该模块:
```
pip install mysql-connector-python
```