在 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 中設置參數。請根據您的實際需求和編程語言進行調整。