简体   繁体   English

c#,使用动态查询

[英]c#, using dynamic queries

How can I use dynamic queries in C# ? 如何在C#中使用动态查询? From what I've searched its similiar to when we use SqlCommand with parameters to prevent sql injection(example below). 从我搜索到的类似于我们使用带有参数的SqlCommand来防止sql注入(例如下面的例子)。

using (SQLiteConnection DB_CONNECTION = new SQLiteConnection(connectionString))
        {
            DB_CONNECTION.Open();
            string sqlquery = "UPDATE table SET Name =@Name, IsComplete=@IsComplete WHERE Key =@Key;";
            int rows = 0;
            using (SQLiteCommand command = new SQLiteCommand(sqlquery, DB_CONNECTION))
            {
                SQLiteParameter[] tableA = { new SQLiteParameter("@Key", todo.Key), new SQLiteParameter("@Name", table.Name), new SQLiteParameter("@IsComplete", table.IsComplete) };
                command.Parameters.AddRange(tableA);
                rows = command.ExecuteNonQuery();
            }
            DB_CONNECTION.Close();
            return (rows);
        }

I'm new to c# and i wondering how can I make this work, thanks in advance. 我是c#的新手,我想知道如何才能完成这项工作,提前谢谢。

Basically just build up the string sqlQuery based on a set of conditions and ensure that the appropriate parameters have been set. 基本上只是根据一组条件构建字符串sqlQuery,并确保已设置适当的参数。 For example, here is some psuedo-C# (not tested for bugs): 例如,这里有一些psuedo-C#(没有测试bug):

//Set to true, so our queries will always include the check for SomeOtherField.
//In reality, use some check in the C# code that you would want to compose your query.
//Here we set some value we want to compare to.
string someValueToCheck = "Some value to compare";

using (SQLiteConnection DB_CONNECTION = new SQLiteConnection(connectionString))
{
    DB_CONNECTION.Open();
    string sqlquery = "UPDATE MyTable SET Name =@Name, IsComplete=@IsComplete WHERE Key =@Key";

    //Replace this with some real condition that you want to use.
    if (!string.IsNullOrWhiteSpace(someValueToCheck))
    {
        sqlquery += " AND SomeOtherField = @OtherFieldValue"
    }

    int rows = 0;
    using (SQLiteCommand command = new SQLiteCommand(sqlquery, DB_CONNECTION))
    {
        //Use a list here since we can't add to an array - arrays are immutable.
        List<SQLiteParameter> tableAList = {
            new SQLiteParameter("@Key", todo.Key),
            new SQLiteParameter("@Name", table.Name),
            new SQLiteParameter("@IsComplete", table.IsComplete) };

        if (!string.IsNullOrWhiteSpace(someValueToCheck)) {
            //Replace 'someValueToCheck' with a value for the C# that you want to use as a parameter.
            tableAList.Add(new SQLiteParameter("@OtherFieldValue", someValueToCheck));
        }

        //We convert the list back to an array as it is the expected parameter type.
        command.Parameters.AddRange(tableAList.ToArray());
        rows = command.ExecuteNonQuery();
    }
    DB_CONNECTION.Close();
    return (rows);
}

In this day and age it would probably be worth looking into LINQ to Entities, as this will help you to compose queries dynamically in your code - for example https://stackoverflow.com/a/5541505/201648 . 在这个时代,可能值得研究LINQ to Entities,因为这将帮助您在代码中动态编写查询 - 例如https://stackoverflow.com/a/5541505/201648

To setup for an existing database - also known as "Database First" - see the following tutorial: https://msdn.microsoft.com/en-au/data/jj206878.aspx 要设置现有数据库 - 也称为“数据库优先” - 请参阅以下教程: https//msdn.microsoft.com/en-au/data/jj206878.aspx

You can skip step 1 since you already have a database, or do the whole tutorial first as practice. 您可以跳过步骤1,因为您已经有了数据库,或者首先将整个教程作为练习。

Here is some psuedo-C# LINQ code to perform roughly the same update as the previous example: 下面是一些psuedo-C#LINQ代码,可以执行与前一个示例大致相同的更新:

//The context you have setup for the ERP database.
using (var db = new ERPContext()) 
{ 

    //db is an Entity Framework database context - see 
    //https://msdn.microsoft.com/en-au/data/jj206878.aspx
    var query = db.MyTable
        .Where(c => c.Key == todo.Key);

    if (!string.IsNullOrWhiteSpace(someValueToCheck))
    {
        //This where is used in conjunction to the previous WHERE,
        //so it's more or less a WHERE condition1 AND condition2 clause.
        query = query.Where(c => c.SomeOtherField == someValueToCheck);
    }

    //Get the single thing we want to update.
    var thingToUpdate = query.First();

    //Update the values.
    thingToUpdate.Name = table.Name;
    thingToUpdate.IsComplete = table.IsComplete;

    //We can save the context to apply these results.
    db.SaveChanges();

}

There is some setup involved with Entity Framework, but in my experience the syntax is easier to follow and your productivity will increase. 实体框架涉及一些设置,但根据我的经验,语法更容易遵循,您的工作效率会提高。 Hopefully this gets you on the right track. 希望这能让你走上正轨。

LINQ to Entites can also map SQL stored procedures if someone one your team objects to using it for performance reasons: LINQ to Entites还可以映射SQL存储过程,如果您的团队中有人出于性能原因而反对使用它:

https://msdn.microsoft.com/en-us/data/gg699321.aspx https://msdn.microsoft.com/en-us/data/gg699321.aspx

OR if you absolutely ust compose custom queries in the C# code this is also permitted in Entity Framework: 或者,如果您绝对在C#代码中撰写自定义查询,则在实体框架中也允许这样做:

https://msdn.microsoft.com/en-us/library/bb738521(v=vs.100).aspx https://msdn.microsoft.com/en-us/library/bb738521(v=vs.100).aspx

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

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