在查询中动态传递值?

时间:2011-06-14 07:08:09

标签: c# sql

我的表syntax中有两列queryTable1。语法包含名为po的数据和名为select * from po_pomas_pur_order_hdr where pomas_pono =的查询。我使用

获得了此查询值
SqlDataAdapter da = new SqlDataAdapter("select query from Table1 where syntax = '" + textBox1.Text + "'", conn);

我的问题是我需要在查询中动态传递另一个值,我使用dataadapter重新检索这个值:

 SqlDataAdapter da1 = new SqlDataAdapter(da.tostring()  +"'"+ textBox1.Text +"'", conn)

生成的查询应如下所示:

 select * from po_pomas_pur_order_hdr where pomas_pono = '2PO/000002/09-10'

但这是不可能的。如何获得这样的查询?有什么建议吗?

4 个答案:

答案 0 :(得分:0)

以这种方式

更安全:dotnetperls

他检查“'”和“\”,检查字段的类型等...

上面示例中的代码(对于插入删除和更新,代码相同):

using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE @Name", connection))
    {
    //
    // Add new SqlParameter to the command.
    //
    command.Parameters.Add(new SqlParameter("Name", dogName));
    //
    // Read in the SELECT results.
    //
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        int weight = reader.GetInt32(0);
        string name = reader.GetString(1);
        string breed = reader.GetString(2);
        Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}", weight, name, breed);
    }
    }

答案 1 :(得分:0)

我建议您使用SqlParametersHere是如何使用DataAdapter和参数的示例。

答案 2 :(得分:0)

SqlDataAdapter用于填充数据集和数据表。您无法使用ToString()获取查询结果。我想你想使用SqlCommand执行你的第一个查询来检索从数据库运行的实际查询,如下所示:

string query = null;
using (var command = new SqlCommand("select query from Table1 where syntax = @Syntax", conn))
{
    command.Parameters.AddWithValue("@Syntax", textBox1.Text);
    query = command.ExecuteScalar(); // this assumes only one query result is returned
}

然后您可以使用数据适配器来填充它:

SqlDataAdapter da1 = new SqlDataAdapter(query  +"'"+ textBox1.Text +"'", conn);

虽然我建议也使用参数。

答案 3 :(得分:0)

如果您有一个DataSet,您打算使用适配器进行填充,并且您调整查询以使用parameters以避免sql injection您应该能够使用以下内容:

string query;
using(var sqlCommand = new SqlCommand(
    "select query from Table1 where syntax=@syntax", conn))
{
    sqlCommand.Parameters.AddWithValue("syntax", textBox1.Text);
    query = (string)sqlCommand.ExecuteScalar();
}

using(var dataAdapter = new SqlDataAdapter())
using(var dataCommand = new SqlCommand(query, conn))
{
    dataCommand.Parameters.AddWithValue("parameter", poNumber);
    dataAdapter.SelectCommand = dataCommand;
    dataAdapter.Fill(myDataSet);
}
相关问题