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

mysql python

作者:躲藏我的霸气   发布日期:2026-04-19   浏览:15

import mysql.connector

# 创建与MySQL数据库的连接
def create_connection():
    connection = mysql.connector.connect(
        host='localhost',  # 数据库主机地址
        user='your_username',  # 数据库用户名
        password='your_password',  # 数据库密码
        database='your_database'  # 要连接的数据库名称
    )
    return connection

# 插入数据到表中
def insert_data(connection, name, age):
    cursor = connection.cursor()
    sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
    val = (name, age)
    cursor.execute(sql, val)
    connection.commit()  # 提交事务
    print(cursor.rowcount, "记录插入成功。")

# 查询表中的数据
def query_data(connection):
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM users")
    results = cursor.fetchall()  # 获取所有记录
    for row in results:
        print(row)

# 主函数
def main():
    connection = create_connection()
    insert_data(connection, 'Alice', 30)
    query_data(connection)
    connection.close()

if __name__ == "__main__":
    main()

解释说明:

  1. 创建连接create_connection 函数用于创建与 MySQL 数据库的连接。你需要根据自己的实际情况修改 hostuserpassworddatabase 参数。
  2. 插入数据insert_data 函数用于向 users 表中插入一条记录。这里使用了参数化查询 (%s) 来防止 SQL 注入攻击。
  3. 查询数据query_data 函数用于从 users 表中查询所有记录,并打印出来。
  4. 主函数main 函数是程序的入口,它调用上述函数来完成连接、插入和查询操作。

请确保你已经安装了 mysql-connector-python 库,可以通过以下命令安装:

pip install mysql-connector-python

上一篇:查看mysql进程

下一篇:mysql 查看binlog

大家都在看

mysqlavg函数保留小数

mysql显示表内容

mysql经纬度距离计算

mysql 加密

存储过程mysql

mysql 1265

mysql with语句

mysql时间加减

mysql查询表名,模糊匹配

brew 启动mysql

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

Laravel 中文站