C# 在SQL Select语句中使用CheckedListBox值
我有两个复选框,标准代码和标准详细信息。初始化时,标准代码从查询填充到数据库C# 在SQL Select语句中使用CheckedListBox值,c#,sql,sql-server,visual-studio,C#,Sql,Sql Server,Visual Studio,我有两个复选框,标准代码和标准详细信息。初始化时,标准代码从查询填充到数据库 InitializeComponent(); SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Project;Integrated Security=True"); conn.Open(); DataSet ds = new DataSet();
InitializeComponent();
SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Project;Integrated Security=True");
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter
("SELECT [StandardCode] FROM [dbo].[StandardCodesAndDetails]", conn);
adapter.Fill(ds);
this.lstBoxStandardCodes.DataSource = ds.Tables[0];
this.lstBoxStandardCodes.DisplayMember = "StandardCode";
conn.Close();
从该复选列表框中,用户可以选择多个标准代码值。在选中或取消选中这些值时,我希望运行一个查询,该查询将使用数据库中的相关标准详细信息填充标准详细信息CheckedListBox,其中一些标准代码具有多个标准详细信息。这是我不知道该怎么写的部分。我不知道如何在这样的SQL语句中包含CheckedListBox值
public string CreateSQL(string userName,string password)
{
string sql="SELECT * FROM Table WHERE";
if(!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
{
sql+=" UserName='"+userName+"' AND Password='"+password+"'";
}
else if(!string.IsNullOrWhiteSpace(userName))
{
sql+=" UserName='"+userName+"'";
}
else if(!string.IsNullOrWhiteSpace(password))
{
sql+=" Password='"+password+"'";
}
else
{
sql=null;
}
return sql;
}
任何帮助都将不胜感激。谢谢。您必须动态创建sql语句,而不是硬编码。例如,我将编写一个基于用户输入的sql语句的方法,如下所示
public string CreateSQL(string userName,string password)
{
string sql="SELECT * FROM Table WHERE";
if(!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
{
sql+=" UserName='"+userName+"' AND Password='"+password+"'";
}
else if(!string.IsNullOrWhiteSpace(userName))
{
sql+=" UserName='"+userName+"'";
}
else if(!string.IsNullOrWhiteSpace(password))
{
sql+=" Password='"+password+"'";
}
else
{
sql=null;
}
return sql;
}
一种解决方案是编写一个接受逗号分隔值的
storeproc
,而不是使用dynamicsql
调用。然后,您可以使用for loops
或foreach
传递多个值。如果所有条件都为false,则sql
为“SELECT*FROM Table WHERE”,这是无效的。还应该始终使用参数来避免sql注入。上面的代码只是作为如何动态创建sql的示例。最好的方法是使用参数和存储过程。另外,请查看