阅读量:0
MySQL 数据库保存代码示例
以下是一个简单的 MySQL 数据库保存代码示例,包括连接数据库、创建表、插入数据、查询数据等基本操作。
import mysql.connector 连接数据库 def connect_db(): try: connection = mysql.connector.connect( host='localhost', user='your_username', password='your_password', database='your_database' ) if connection.is_connected(): print("MySQL Connection is successful") return connection except mysql.connector.Error as e: print("Error while connecting to MySQL", e) return None 创建表 def create_table(connection): cursor = connection.cursor() create_table_query = """ CREATE TABLE IF NOT EXISTS employees ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, age INT NOT NULL, department VARCHAR(255) NOT NULL ); """ try: cursor.execute(create_table_query) print("Table created successfully") except mysql.connector.Error as e: print("Failed to create table", e) 插入数据 def insert_data(connection, name, age, department): cursor = connection.cursor() insert_query = """ INSERT INTO employees (name, age, department) VALUES (%s, %s, %s); """ try: cursor.execute(insert_query, (name, age, department)) connection.commit() print("Data inserted successfully") except mysql.connector.Error as e: print("Failed to insert data", e) 查询数据 def query_data(connection): cursor = connection.cursor() query = "SELECT * FROM employees;" try: cursor.execute(query) results = cursor.fetchall() for row in results: print(row) except mysql.connector.Error as e: print("Failed to fetch data", e) 主程序 if __name__ == "__main__": connection = connect_db() if connection: create_table(connection) insert_data(connection, 'John Doe', 30, 'HR') insert_data(connection, 'Jane Smith', 25, 'IT') query_data(connection) connection.close() print("MySQL connection is closed")
代码说明:
1、连接数据库:connect_db
函数用于连接到 MySQL 数据库。
2、创建表:create_table
函数用于创建一个名为employees
的表,其中包含id
、name
、age
和department
字段。
3、插入数据:insert_data
函数用于向employees
表中插入新记录。
4、查询数据:query_data
函数用于查询employees
表中的所有记录。
5、主程序:在主程序中,首先连接到数据库,然后创建表,插入数据,查询数据,最后关闭数据库连接。
确保在运行此代码之前,你已经有一个运行中的 MySQL 数据库,并且已经替换了your_username
、your_password
和your_database
为实际的数据库用户名、密码和数据库名称。