如何在c#中的where子句中替换变量

时间:2016-01-27 17:11:49

标签: c# asp.net .net oracle

我有一个oracle查询,它将从数据库中获取数据并在gridview中动态显示它们。使用的查询是Attempting to gather dependencies information for package 'Naos.Packaging.NuGet.1.0.5' with respect to project 'Naos.Deployment.Core', targeting '.NETFramework,Version=v4.5' Attempting to resolve dependencies for package 'Naos.Packaging.NuGet.1.0.5' with DependencyBehavior 'Lowest' Resolving actions to install package 'Naos.Packaging.NuGet.1.0.5' Resolved actions to install package 'Naos.Packaging.NuGet.1.0.5' Removed package 'NuGet.Core.2.8.6' from 'packages.config' Successfully uninstalled 'NuGet.Core.2.8.6' from Naos.Deployment.Core Adding package 'Naos.Packaging.Domain.1.0.5' to folder 'C:\Users\suraj\Documents\GitHub\Naos.Deployment\packages' Added package 'Naos.Packaging.Domain.1.0.5' to folder 'C:\Users\suraj\Documents\GitHub\Naos.Deployment\packages' Added package 'Naos.Packaging.Domain.1.0.5' to 'packages.config' Successfully installed 'Naos.Packaging.Domain 1.0.5' to Naos.Deployment.Core Adding package 'NuGet.Configuration.3.3.0' to folder 'C:\Users\suraj\Documents\GitHub\Naos.Deployment\packages' Added package 'NuGet.Configuration.3.3.0' to folder 'C:\Users\suraj\Documents\GitHub\Naos.Deployment\packages' Install failed. Rolling back... Package 'NuGet.Configuration.3.3.0 : ' does not exist in project 'Naos.Deployment.Core' Removed package 'Naos.Packaging.Domain.1.0.5 : ' from 'packages.config' Package 'NuGet.Core.2.8.6' already exists in folder 'C:\Users\suraj\Documents\GitHub\Naos.Deployment\packages' Added package 'NuGet.Core.2.8.6' to 'packages.config' Removing package 'NuGet.Configuration.3.3.0 : ' from folder 'C:\Users\suraj\Documents\GitHub\Naos.Deployment\packages' Removed package 'NuGet.Configuration.3.3.0 : ' from folder 'C:\Users\suraj\Documents\GitHub\Naos.Deployment\packages' Removing package 'Naos.Packaging.Domain.1.0.5 : ' from folder 'C:\Users\suraj\Documents\GitHub\Naos.Deployment\packages' Removed package 'Naos.Packaging.Domain.1.0.5 : ' from folder 'C:\Users\suraj\Documents\GitHub\Naos.Deployment\packages' Failed to add reference to 'System.Globalization'. Please make sure that it is in the Global Assembly Cache. ========== Finished ========== 。变量以?开头?是在运行时填充的占位符。假设在这里我通过选择下拉来提取占位符并将其设置为select *from Employee where Location=?Location and Age=?Age and Marks=?Marks。我需要一个逻辑来将我创建的值插入到占位符中,如果有些东西错过了例如这里Location='Chemmad' and Marks='100'丢失,我必须捕获丢失的那个。简而言之,我有一个查询下拉列表

Age

我在运行时获得了像

这样的占位符的值
string query = "select *from Employee where Location=?Location and Age=?Age and Marks=?Marks";

所以我想用占位符替换值,同时需要找到丢失的值,所以这里string values = "Location='Chemmad' and Marks='100'";

Age

我在oracle数据库本身存储了所有查询组合:)并在运行时获取并替换值。我想我必须找到=符号的位置并需要从任何一方找到这些单词?

3 个答案:

答案 0 :(得分:1)

您应该使用SqlCommand.Parameters将参数传递给您的查询,如下所示。使用string.Format代替您的代码容易受到SQL注入。

string commandText = "select *from Employee where Location=@Location and Age=@Age and Marks=@Marks;"

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(commandText, connection);
    command.Parameters.Add("@Location", SqlDbType.Char);
    command.Parameters["@Location"].Value = Location;

    command.Parameters.Add("@Age", SqlDbType.Int);
    command.Parameters["@Age"].Value = Age;

    command.Parameters.Add("@Marks", SqlDbType.Int);
    command.Parameters["@Marks"].Value = Marks;



    try
    {
        connection.Open();
        Int32 rowsAffected = command.ExecuteNonQuery();
        Console.WriteLine("RowsAffected: {0}", rowsAffected);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
  }     

答案 1 :(得分:1)

string strValues = "Location='Chemmad' and  Marks='100'"; // this is bad and will cause sql injection attacks.
// what you actually want is an object(s) that you can use in the parameterized query. depending on your input you then dynamically create the where part of your string. something like this:
var parameterValues = new
{
    Location = "Chemmad",
    Marks = 100
};


const string searchTerm = " where ";
var query = @"select * from Employee where Location=?Location and Age=?Age and Marks=?Marks";
var part1 = query.Substring(0, query.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase));
// the following line is not necessary and won't be used. It just illustrates how to get the remainder of the query.
var part2 = query.Substring(query.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase) + searchTerm.Length, query.Length - part1.Length - searchTerm.Length);

var myDynamicQuery = part1 + searchTerm;
myDynamicQuery = myDynamicQuery + "Location = :location ";
myDynamicQuery = myDynamicQuery + "AND Marks = :marks ";

myDynamicQuery现在包含字符串:select * from Employee where Location = :location AND Marks = :marks

下一步

  1. 创建您的oracle连接
  2. 制作您的DbParameters
  3. 对oracle命令对象执行查询
  4. 有关如何从.NET正确创建Oracle连接并使用参数化查询,请参阅this article

答案 2 :(得分:1)

这是使用ODP.net的Oracle参数化查询。就像Jaco的回应一样,这比串替换更好,原因有很多:

  1. 防止SQL注入
  2. 管理数据类型(不需要在C#DateTime => Oracle的日期上进行任何转换)
  3. 消除SQL中引用的难度(撇号,引号,回车等)
  4. 示例:

    string query = "select * from Employee where " +
        "Location= :LOC and Age = :AGE and Marks = :MARKS";
    
    OracleCommand cmd = new OracleCommand(query);
    cmd.Parameters.Add("LOC", "Chemmad");
    cmd.Parameters.Add("AGE", 125);
    cmd.Parameters.Add("MARKS", "100");
    
    OracleDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        object firstField = reader.GetValue(0);
    }
    
    reader.Close();
    

    数据类型最好的Add,特别是当你有多个要分配的值时(比如在插入或更新中),但是如果你只有一组参数,那么Add还允许在单个语句中声明和分配参数。在某些实现中,这是AddWithValue,但我认为在Oracle中它只是Add的重载。

    另请注意,与SQL Server不同,使用Oracle时,您在SQL中使用:而不是@,并在声明实际OracleParameters时将该字符保留为关闭。 / p>