是指在服务器端与数据库进行交互的代码。以下是一个示例代码:
import mysql.connector
# 连接数据库
def connect_to_database():
try:
connection = mysql.connector.connect(
host="数据库主机地址",
user="数据库用户名",
password="数据库密码",
database="数据库名称"
)
return connection
except mysql.connector.Error as error:
print("连接数据库失败:{}".format(error))
return None
# 查询数据
def execute_query(query):
connection = connect_to_database()
if connection is not None:
try:
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
return result
except mysql.connector.Error as error:
print("执行查询失败:{}".format(error))
finally:
if connection.is_connected():
cursor.close()
connection.close()
else:
return None
# 插入数据
def execute_insert(query, values):
connection = connect_to_database()
if connection is not None:
try:
cursor = connection.cursor()
cursor.execute(query, values)
connection.commit()
print("插入数据成功")
except mysql.connector.Error as error:
print("执行插入失败:{}".format(error))
finally:
if connection.is_connected():
cursor.close()
connection.close()
else:
return None
# 更新数据
def execute_update(query, values):
connection = connect_to_database()
if connection is not None:
try:
cursor = connection.cursor()
cursor.execute(query, values)
connection.commit()
print("更新数据成功")
except mysql.connector.Error as error:
print("执行更新失败:{}".format(error))
finally:
if connection.is_connected():
cursor.close()
connection.close()
else:
return None
# 删除数据
def execute_delete(query):
connection = connect_to_database()
if connection is not None:
try:
cursor = connection.cursor()
cursor.execute(query)
connection.commit()
print("删除数据成功")
except mysql.connector.Error as error:
print("执行删除失败:{}".format(error))
finally:
if connection.is_connected():
cursor.close()
connection.close()
else:
return None
这段代码使用了Python的mysql.connector库来连接和操作MySQL数据库。其中,connect_to_database()
函数用于连接数据库,execute_query()
函数用于执行查询语句并返回结果,execute_insert()
函数用于执行插入语句,execute_update()
函数用于执行更新语句,execute_delete()
函数用于执行删除语句。
这些代码可以根据具体的需求进行修改和扩展,例如添加数据验证、错误处理等。在实际应用中,可以根据具体的数据库类型和需求选择适合的数据库连接库和语言。
领取专属 10元无门槛券
手把手带您无忧上云