在Python中调用MySQL数据库,通常使用mysql-connector-python
库,以下是详细的步骤和代码示例:
1. 安装mysql-connector-python
库
你需要安装mysql-connector-python
库,可以使用pip进行安装:
pip install mysql-connector-python
连接到MySQL数据库
你需要连接到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")
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 """ connection = create_connection("your_host", "your_username", "your_password", "your_database") execute_query(connection, create_table_query)
插入数据
insert_users_query = """ INSERT INTO users (name, age, gender, nationality) VALUES ('James', 25, 'male', 'USA'); """ execute_query(connection, insert_users_query)
查询数据
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")
select_users_query = "SELECT * from users" users = read_query(connection, select_users_query) for user in users: print(user)
关闭连接
完成所有操作后,记得关闭数据库连接:
if connection.is_connected(): connection.close() print("The connection is closed")
是使用Python调用MySQL数据库的基本步骤,通过这些步骤,你可以创建数据库连接、执行SQL查询以及处理结果,确保在使用前替换示例中的占位符(如your_host
,your_username
,your_password
,your_database
)为实际的数据库信息。
小伙伴们,上文介绍python 调用mysql数据库_Mysql数据库的内容,你了解清楚吗?希望对你有所帮助,任何问题可以给我留言,让我们下期再见吧。
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/90404.html