要在Python中连接MySQL,可以使用mysql-connector-python库。首先,确保已经安装了这个库,如果没有安装,可以通过pip安装:
pip install mysql-connector-python
以下是一个简单的示例,展示了如何使用mysql-connector-python连接到MySQL数据库并执行查询
import mysql.connector
# 连接数据库
config1 = {
'user':'your_username',
'password':'your_password',
'host':'localhost',
'port':'3306',
'database':'your_database'
}
conn = mysql.connector.connect(**config1)
# 创建一个游标对象
cursor = conn.cursor()
# 执行一个查询
query = ("SELECT * FROM account") # 查询语句
cursor.execute(query) # 执行查询
result1 = cursor.fetchall() # 取出所有数据
print(len(result1)) # 输出结果集的行数
if len(result1) > 0: # 判断结果集是否为空
for row in result1: # 遍历结果集
print(row[1]) # 输出结果集的第一列
# 关闭游标和连接
cursor.close()
# result1 = cursor.fetchone() # 取出第一条数据
# print(result1) # 输出第一条数据
# 关闭游标和连接
# print(result1[1])
#conn.commit() # 提交事务
# 关闭游标和连接
cursor.close()
conn.close()请确保替换your_username, your_password, localhost, your_database, 和your_table为你的MySQL数据库的实际登录凭据和你想要查询的表名。
转载请注明:雪宝小站-雪宝的小知识库 » Python学习 » Python 连接Mysql

