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()
create_connection 函数用于创建与 MySQL 数据库的连接。你需要根据自己的实际情况修改 host、user、password 和 database 参数。insert_data 函数用于向 users 表中插入一条记录。这里使用了参数化查询 (%s) 来防止 SQL 注入攻击。query_data 函数用于从 users 表中查询所有记录,并打印出来。main 函数是程序的入口,它调用上述函数来完成连接、插入和查询操作。请确保你已经安装了 mysql-connector-python 库,可以通过以下命令安装:
pip install mysql-connector-python
上一篇:查看mysql进程
下一篇:mysql 查看binlog
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站