可以通过以下步骤在c#代码中使用参数运行SQL查询:
创建SqlConnection对象,连接到数据库。
创建SqlCommand对象,设置SQL查询语句,并添加参数字符串。
SqlCommand command = new SqlCommand("SELECT * FROM Customers WHERE Country = @Country", connection);
command.Parameters.Add("@Country", SqlDbType.NVarChar).Value = "USA";
执行查询并获取结果。
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) { Console.WriteLine(reader.GetString(0)); }
完整示例代码如下:
using System; using System.Data; using System.Data.SqlClient;
class Program { static void Main() { string connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM Customers WHERE Country = @Country", connection);
command.Parameters.Add("@Country", SqlDbType.NVarChar).Value = "USA";
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
}
}
}