阅读量:4
在C#中构建动态SQL查询可以使用字符串拼接的方式或者使用参数化查询。以下是一个使用参数化查询的示例:
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=True";
string query = "SELECT * FROM YourTable WHERE Column1 = @param1";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@param1", "Value1");
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["Column1"]);
}
}
}
}
}
}
在这个示例中,我们使用参数化查询来构建动态SQL查询。首先定义了连接字符串和查询语句,然后创建了一个SqlConnection和SqlCommand对象,并通过AddWithValue方法为查询参数添加了一个值。最后执行查询并读取结果。这种方式比直接拼接字符串更安全,能够防止SQL注入攻击。
以上就是关于“C#如何构建动态SQL查询”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm