Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python mysql数据库

作者:倾尽尘光暖流年   发布日期:2025-04-28   浏览:91

import mysql.connector

# 连接到 MySQL 数据库
def connect_to_database():
    try:
        connection = mysql.connector.connect(
            host='localhost',       # 数据库主机地址
            user='your_username',   # 数据库用户名
            password='your_password',  # 数据库密码
            database='your_database'  # 要连接的数据库名称
        )
        if connection.is_connected():
            print("成功连接到数据库")
            return connection
    except mysql.connector.Error as err:
        print(f"连接失败: {err}")
        return None

# 插入数据到表中
def insert_data(connection, table, data):
    cursor = connection.cursor()
    sql = f"INSERT INTO {table} (name, age) VALUES (%s, %s)"
    cursor.execute(sql, data)
    connection.commit()
    print(f"插入数据: {data}")

# 查询数据
def query_data(connection, table):
    cursor = connection.cursor()
    sql = f"SELECT * FROM {table}"
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
        print(row)

# 关闭数据库连接
def close_connection(connection):
    if connection.is_connected():
        connection.close()
        print("数据库连接已关闭")

# 示例代码
if __name__ == "__main__":
    conn = connect_to_database()
    if conn:
        # 插入示例数据
        insert_data(conn, 'users', ('Alice', 30))
        # 查询表中的数据
        query_data(conn, 'users')
        # 关闭连接
        close_connection(conn)

解释说明:

  1. 连接到 MySQL 数据库:使用 mysql.connector.connect() 方法连接到 MySQL 数据库。需要提供主机地址、用户名、密码和数据库名称。
  2. 插入数据:通过 INSERT INTO SQL 语句将数据插入到指定表中,并使用 connection.commit() 提交事务。
  3. 查询数据:使用 SELECT * FROM SQL 语句查询表中的所有数据,并通过 cursor.fetchall() 获取结果集。
  4. 关闭连接:在完成操作后,确保关闭数据库连接以释放资源。

上一篇:mysql四种索引类型

下一篇:mysql schema

大家都在看

mysqlavg函数保留小数

mysql经纬度距离计算

存储过程mysql

mysql with语句

mysql时间加减

brew 启动mysql

unsigned在mysql中是什么意思

mysql 插入更新

python mysql update

mysql 查看权限

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站