网页输入数据到MySQL是指通过Web应用程序将用户在网页上输入的数据存储到MySQL数据库中。这个过程通常涉及以下几个步骤:
原因:
解决方法:
try-catch
块捕获SQL异常,查看具体的错误信息。import mysql.connector
try:
# 连接数据库
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="mydatabase"
)
cursor = conn.cursor()
# 插入数据
sql = "INSERT INTO users (name, email) VALUES (%s, %s)"
val = ("John Doe", "john@example.com")
cursor.execute(sql, val)
# 提交事务
conn.commit()
print("数据插入成功")
except mysql.connector.Error as err:
print(f"数据插入失败: {err}")
finally:
# 关闭连接
if conn.is_connected():
cursor.close()
conn.close()
print("数据库连接已关闭")
原因:
解决方法:
import mysql.connector
try:
# 连接数据库,设置连接超时时间为30秒
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="mydatabase",
connection_timeout=30
)
cursor = conn.cursor()
# 执行SQL操作
cursor.execute("SELECT * FROM users")
# 获取结果
result = cursor.fetchall()
print(result)
except mysql.connector.Error as err:
print(f"数据库连接失败: {err}")
finally:
# 关闭连接
if conn.is_connected():
cursor.close()
conn.close()
print("数据库连接已关闭")
原因:
解决方法:
import mysql.connector
try:
# 连接数据库
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="mydatabase"
)
cursor = conn.cursor()
# 使用参数化查询防止SQL注入
user_input = "John Doe"
sql = "SELECT * FROM users WHERE name = %s"
cursor.execute(sql, (user_input,))
# 获取结果
result = cursor.fetchall()
print(result)
except mysql.connector.Error as err:
print(f"数据库查询失败: {err}")
finally:
# 关闭连接
if conn.is_connected():
cursor.close()
conn.close()
print("数据库连接已关闭")
领取专属 10元无门槛券
手把手带您无忧上云