在 SQL Server 中,使用参数化查询可以提高安全性和性能
CREATE PROCEDURE GetEmployeeById
@EmployeeId INT
AS
BEGIN
SELECT * FROM Employees WHERE EmployeeId = @EmployeeId;
END;
要调用此存储过程并传递参数,请使用以下语句:
EXEC GetEmployeeById @EmployeeId = 1;
首先,确保已安装 System.Data.SqlClient
。
using System.Data.SqlClient;
string connectionString = "your_connection_string";
string query = "SELECT * FROM Employees WHERE EmployeeId = @EmployeeId";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
// 添加参数
command.Parameters.AddWithValue("@EmployeeId", 1);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// 处理查询结果
}
}
}
}
pyodbc
库):首先,确保已安装 pyodbc
。
import pyodbc
connection_string = "your_connection_string"
query = "SELECT * FROM Employees WHERE EmployeeId = ?"
connection = pyodbc.connect(connection_string)
cursor = connection.cursor()
# 添加参数
params = (1,)
cursor.execute(query, params)
for row in cursor:
# 处理查询结果
cursor.close()
connection.close()
这些示例展示了如何在 SQL Server 中设置参数。请根据您的实际需求和编程语言进行调整。