简体   繁体   English

使用子查询asp.net插入查询

[英]Insert query with sub query asp.net

I need to insert text from a asp.net web form. 我需要从asp.net网络表单中插入文本。 The final insert in my string needs to insert the the value from a column based on a treeview checked value. 我字符串中的最后一个插入内容需要根据treeview检查的值从一列中插入值。 I need to run a sub query in my insert statement that avoids SQL injection. 我需要在我的插入语句中运行一个子查询,以避免SQL注入。 The current code inserts a null value rather than the value from the select statement. 当前代码插入一个空值,而不是select语句中的值。

This is my code: 这是我的代码:

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();
    }
}

According to MSDN, you can user dynamic queries similar to the following ( http://ud.ht/bDhf Check Step 3 ) 根据MSDN,您可以使用类似于以下内容的用户动态查询( http://ud.ht/bDhf检查步骤3

First create an object of the "SqlDataAdaptor" class. 首先创建“ SqlDataAdaptor”类的对象。 Then for each variable, assign an arbitrary name and add it to the command. 然后,为每个变量分配一个任意名称,并将其添加到命令中。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM