C# 在Appsettings中使用动态where子句获取键的值

C# 在Appsettings中使用动态where子句获取键的值,c#,asp.net,appsettings,C#,Asp.net,Appsettings,我想在web.config项目(ASP.NET和C#)的appSettings部分中,通过动态where子句获取key的值,如下所示: key="test" value="Select * from table where id=Textbox1.Text" // Get sql query and add where clause to it. string sqlString = System.Configuration.ConfigurationManager.AppSettings["

我想在
web.config
项目(ASP.NET和C#)的
appSettings
部分中,通过动态where子句获取key的值,如下所示:

key="test" value="Select * from table where id=Textbox1.Text"
// Get sql query and add where clause to it.
string sqlString = System.Configuration.ConfigurationManager.AppSettings["test"] + " where id=@id";


// Execute sqlString 
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();

SqlParameter param  = new SqlParameter();
param.ParameterName = "@id";
param.Value = Textbox1.Text;
cmd.Parameters.Add(param);
SqlDataReader reader;

cmd.CommandText = sqlString;
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;

sqlConnection1.Open();

reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.

sqlConnection1.Close();

我如何才能做到这一点?

您可以这样做:

key="test" value="Select * from table where id=Textbox1.Text"
// Get sql query and add where clause to it.
string sqlString = System.Configuration.ConfigurationManager.AppSettings["test"] + " where id=@id";


// Execute sqlString 
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();

SqlParameter param  = new SqlParameter();
param.ParameterName = "@id";
param.Value = Textbox1.Text;
cmd.Parameters.Add(param);
SqlDataReader reader;

cmd.CommandText = sqlString;
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;

sqlConnection1.Open();

reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.

sqlConnection1.Close();
编辑


C#对于防止,停止执行执行此操作的命令。你应该使用
SqlParameter

这是一个诡计,打开SQL注入攻击感谢你的回答。我使用下面的代码,但它没有显示任何内容:var sql1=System.Configuration.ConfigurationManager.AppSettings[“test”]+“where id=“+TextBox1.Text;string conString=ConfigurationManager.ConnectionStrings[“ConnectionString1”]。ConnectionString;使用(SqlConnection con=newsqlconnection(consting)){SqlCommand cmd2=newsqlcommand(sql1,con);cmd2.CommandType=CommandType.Text;但是没有TextBox1.Text,它会显示数据。是否正确?@helal请
upvote
接受这个答案,如果它对你有帮助,那么人们就会知道这是正确的答案并帮助他们。@Jeremythonpson是的,我知道这可能很危险,但他可能不得不这么做这样做。不,他没有。如果不是存储过程,就使用参数化查询,不要在这里给出狗屎建议。