我需要从asp.net Web表单插入文本。我的字符串中的最后一个插入需要根据树视图选中的值插入列中的值。我需要在insert语句中运行一个子查询,以避免SQL注入。当前代码插入空值而不是select语句中的值。
这是我的代码:
string content = TxtContent.Text;
string Pagename = txtKeywords.Text;
string title = TxtPageName.Text;
string description = TxtDescription.Text;
string URL = TxtPageName.Text;
string Keywords = txtKeywords.Text;
string tree = TreeView1.SelectedValue;
string query = @"INSERT INTO Menus([content], [Pagename], [title], [description], [Keywords], [url], [ParentMenuId]) " + "Values('" + content + "', '" + Pagename + "', '" + title + "', '" + description + "', '" + Keywords + "', '/" + URL + "', (Select [parentmenuid] from [menus] where [title] ='"+tree+"'))";
using (SqlConnection connection = new SqlConnection("Data Source=MYConnectionString"))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.ExecuteNonQuery();
}
}
答案 0 :(得分:0)
根据MSDN,您可以使用类似以下内容的动态查询(http://ud.ht/bDhf检查第3步)
首先创建“SqlDataAdaptor”类的对象。然后为每个变量分配一个任意名称并将其添加到命令中。
using System.Data;
using System.Data.SqlClient;
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet userDataset = new DataSet();
SqlDataAdapter myDataAdapter = new SqlDataAdapter(
"SELECT au_lname, au_fname FROM Authors WHERE au_id = @au_id",
connection);
myDataAdapter.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);
myDataAdapter.SelectCommand.Parameters["@au_id"].Value = SSN.Text;
myDataAdapter.Fill(userDataset);
}