用phython 写一个连接数据库的代码
以下是使用Python连接数据库的示例代码:
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建数据库表
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
# 插入数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
# 提交更改
mydb.commit()
# 输出数据
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
这个示例代码连接了一个名为 "yourdatabase" 的MySQL数据库,创建了一个名为 "customers" 的表,并插入了一条数据。最后输出了表中的所有数据。请确保将示例代码中的 "yourusername" 和 "yourpassword" 替换为您的实际数据库用户名和密码。
原文地址: https://www.cveoy.top/t/topic/bVQP 著作权归作者所有。请勿转载和采集!