一推网

当前位置: 首页 > 知识问答 > MySQL保存数据库代码如何确保数据安全性和高效性?

知识问答

MySQL保存数据库代码如何确保数据安全性和高效性?

2025-09-21 16:21:57 来源:互联网转载

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 的表,其中包含idnameagedepartment 字段。

3、插入数据insert_data 函数用于向employees 表中插入新记录。

4、查询数据query_data 函数用于查询employees 表中的所有记录。

5、主程序:在主程序中,首先连接到数据库,然后创建表,插入数据,查询数据,最后关闭数据库连接。

确保在运行此代码之前,你已经有一个运行中的 MySQL 数据库,并且已经替换了your_usernameyour_passwordyour_database 为实际的数据库用户名、密码和数据库名称。

上一篇:音乐外链下载:提升网站流量与品牌知名度的终结指南

下一篇:2023年腾讯云服务器续费优惠券