在Python中调用MySQL数据库,通常使用mysql-connector-python库,以下是详细的步骤和代码示例:

1. 安装mysql-connector-python库
你需要安装mysql-connector-python库,可以使用pip进行安装:
pip install mysql-connector-python
导入库并建立连接
在你的Python脚本中导入库并建立与MySQL数据库的连接。
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 执行SQL查询
一旦建立了连接,你可以执行SQL查询来操作数据库。

def execute_query(connection, query):
cursor = connection.cursor()
try:
cursor.execute(query)
connection.commit()
print("Query executed successfully")
except Error as e:
print(f"The error '{e}' occurred") 读取数据
如果你需要从数据库中读取数据,可以使用以下函数:
def read_query(connection, query):
cursor = connection.cursor()
result = None
try:
cursor.execute(query)
result = cursor.fetchall()
return result
except Error as e:
print(f"The error '{e}' occurred") 关闭连接
完成所有操作后,不要忘记关闭数据库连接。
def close_connection(connection):
if connection:
connection.close()
print("The connection is closed") 示例用法
下面是一个完整的示例,展示如何使用上述函数连接到MySQL数据库,执行查询,并读取数据。
Replace the placeholders with your actual database credentials and details
host_name = "your_host"
user_name = "your_username"
user_password = "your_password"
db_name = "your_database"
Create a database connection
connection = create_connection(host_name, user_name, user_password, db_name)
Example query to create a table
create_table_query = """
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT,
name TEXT NOT NULL,
age INT,
gender TEXT,
nationality TEXT,
PRIMARY KEY (id)
) ENGINE = InnoDB;
"""
execute_query(connection, create_table_query)
Example query to insert data into the table
insert_users_query = """
INSERT INTO users (name, age, gender, nationality) VALUES
('James', 25, 'male', 'USA'),
('Leila', 32, 'female', 'France'),
('Brigitte', 35, 'female', 'Germany');
"""
execute_query(connection, insert_users_query)
Example query to read data from the table
select_users_query = "SELECT * FROM users"
users = read_query(connection, select_users_query)
for user in users:
print(user)
Close the connection
close_connection(connection) 通过以上步骤,你可以在Python中成功调用MySQL数据库,主要步骤包括安装库、建立连接、执行查询、读取数据以及关闭连接,希望这些信息对你有所帮助!

以上就是关于“python调用mysql_Python”的问题,朋友们可以点击主页了解更多内容,希望可以够帮助大家!
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/86447.html