前言
在python项目开发中,我们经常使用多种数据库存储数据,常用的有:
MySQL:mysql-connector-python, PyMySQL
PostgreSQL:psycopg2
SQLite:sqlite3(标准库)
下面是一个通用的步骤示例,展示如何使用Python连接数据库并执行查询。这里我们以MySQL数据库为例,使用mysql-connector-python库。
步骤一:安装库
首先,确保你已经安装了mysql-connector-python库。如果没有安装,可以使用以下命令进行安装:
pip install mysql-connector-python
步骤二:连接数据库
接下来,编写代码来连接到数据库。
import mysql.connector
from mysql.connector import Error
def create_connection(host_name, user_name, user_password, db_name):
connection = None
try:
connection = mysql.connector.connect(
host=host_name,
user=user_name,
passwd=user_password,
database=db_name
)
print(“Connection to MySQL DB successful”)
except Error as e:
print(f"The error ‘{e}’ occurred")
return connection
步骤三:执行查询
定义一个函数来执行查询:
def execute_query(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
connection.commit()
print(“Query executed suc


882

被折叠的 条评论
为什么被折叠?



