当前位置:首页 > 行业动态 > 正文

连接mysql数据库代码

首先,你需要安装MySQL Connector,然后使用以下代码连接到数据库:,,“ python,import mysql.connector,,cnx = mysql.connector.connect(user='用户名', password='密码', host='主机地址', database='数据库名'),cursor = cnx.cursor(),“

要连接MySQL数据库,首先需要安装Python的MySQL连接器,然后使用以下代码进行连接:

连接mysql数据库代码  第1张

1、安装MySQL连接器:

pip install mysqlconnectorpython

2、连接MySQL数据库的代码:

import mysql.connector
创建连接
cnx = mysql.connector.connect(
    host="数据库地址",  # localhost
    user="用户名",  # root
    password="密码",
    database="数据库名"
)
创建游标
cursor = cnx.cursor()
执行SQL查询
query = "SELECT * FROM 表名"
cursor.execute(query)
获取查询结果
results = cursor.fetchall()
打印查询结果
for row in results:
    print(row)
关闭游标和连接
cursor.close()
cnx.close()

请将上述代码中的数据库地址、用户名、密码和数据库名替换为实际的值。

0