阅读量:126
要连接MySQL数据库,首先需要安装MySQL数据库驱动程序。在Python中,可以使用pymysql或mysql-connector-python等库来连接MySQL数据库。
以下是使用pymysql库连接MySQL数据库的步骤:
-
安装
pymysql库:pip install pymysql -
导入
pymysql库:import pymysql -
建立数据库连接:
conn = pymysql.connect( host='localhost', # 数据库主机地址 port=3306, # 数据库端口号,默认为3306 user='root', # 数据库用户名 password='password', # 数据库密码 db='database_name', # 数据库名 charset='utf8mb4', # 字符集 cursorclass=pymysql.cursors.DictCursor # 游标类型,这里使用字典类型的游标 ) -
创建游标对象:
cursor = conn.cursor() -
执行SQL查询:
cursor.execute("SELECT * FROM table_name") result = cursor.fetchall() -
关闭游标和数据库连接:
cursor.close() conn.close()
这样就可以连接上MySQL数据库并执行SQL查询了。根据具体的需求,可以进一步根据pymysql库提供的方法来插入、更新、删除数据等操作。