简体   繁体   English

带方法值的参数化插入查询

[英]Parameterized Insert Query with method value

I have two methods. 我有两种方法。 When I call the method glass, I need to insert the value in a query. 当我调用玻璃方法时,我需要在查询中插入值。 How can I insert the value of a method in a query? 如何在查询中插入方法的值?

I'm working with MVC, C# and SQL Server. 我正在使用MVC,C#和SQL Server。

The code I tried: in this method call a method glas 我尝试的代码:在此方法中调用方法glas

RController re = new RController();
re.Glas(C_E);
string insert = "INSERT INTO dbo.MEP (R1) VALUES (@code)";

using (SqlCommand command = new SqlCommand(insert, con))
{
    command.Parameters.AddWithValue("@code", "HERE METHOD GLAS");
    con.Open();
    int result = command.ExecuteNonQuery();
}

Method GLAS returns a string. 方法GLAS返回一个字符串。 That string is what I need to insert in a query. 该字符串是我需要在查询中插入的字符串。 The query is located in another controller method (Rcontroller). 该查询位于另一个控制器方法(Rcontroller)中。

public void GLAS(string C_E)
{
     // more code
     if (i > 0)
     {
          string glas1 =  "OK";
     }
     else
     {
          string glas1 = "Fail"; 
     }
}

Your current method is void and not returning any value. 您当前的方法void并且不返回任何值。 You may pass the value by ref, or just simply change your method to return value: 您可以通过ref传递值,也可以只是将方法更改为返回值:

public string GLAS(string C_E)
{
     //more code
     string glas1 = "OK"; 
     if (i > 0)
     {
          glas1 =  "OK";
     }
     else
     {
          glas1 = "Fail"; 
     }
     return glas1;
}

Then you can use it like: 然后您可以像这样使用它:

command.Parameters.AddWithValue("@code", GLAS(C_E));

Also, it is advised not to use .AddWithValue and you may use Parameters.Add() instead like: 另外,建议不要使用.AddWithValue而可以使用Parameters.Add()例如:

command.Parameters.Add("@code", SqlDbType.VarChar).Value = GLAS(C_E);

To elaborate on this subject, you have several choices. 要详细说明这个主题,您有几种选择。 Some of them have already been elaborated upon. 其中一些已经详细说明。 The following approaches exists, Add , AddWithValue , and an entire parameter collection. 存在以下方法: AddAddWithValue和整个参数集合。 This provides flexibility, but also you mention to return a value. 这提供了灵活性,但您也提到要返回一个值。

So to approach the initial parameter aspect. 因此要接近初始参数方面。

  • Add: You define the parameter, the type in SQL, and value. 添加:您定义参数,SQL类型和值。 This alleviates potential database inference issues. 这样可以减轻潜在的数据库推断问题。 You pass a value which is an integer but SQL believes it should be a decimal as defined. 您传递的值是整数,但SQL认为该值应为所定义的十进制。

  • AddWithValue: SQL will auto infer the type, simply pass a value and parameter. AddWithValue:SQL将自动推断类型,只需传递值和参数即可。

  • Parameter Collection: You define all of your parameters in advance, then simply pass to your SqlCommand . 参数集合:您可以预先定义所有参数,然后只需将其传递给SqlCommand

A sample method would be: 一个示例方法是:

public class DatabaseContext : IDbRepository { private readonly string dbConnection; 公共类DatabaseContext:IDbRepository {私有只读字符串dbConnection;

 public DatabaseContext(IConfiguration configuration) => dbConnection = configuration.GetConnectionString("dbConnection");

 public bool Insert(string query, params SqlParameter[] parameters)
 {
      // If no parameters, then you really are not inserting.  Handle exception.

      using(var connection = new SqlConnection(dbConnection))
           using(var command = new SqlCommand(connection, query))
           {
                connection.Open();
                command.Parameters.AddRange(parameters);
                return (command.ExecuteNonQuery() > 0);
           }
 }

So in essence you would call your context, pass the query, the parameters, then execute your query. 因此,从本质上讲,您将调用上下文,传递查询,参数,然后执行查询。 But you have it returning a boolean, rather than a conditional check to assign a success or failure. 但是您可以返回布尔值,而不是有条件的检查来分配成功或失败。 When you call, you would know it succeeded, so you could pass a valid status code back ie HttpStatusCode.Ok . 调用时,您将知道它已成功完成,因此您可以将有效的状态代码(即HttpStatusCode.Ok传递回去。

But you could also wrap in a factory, or clean the approach a bit when interacting. 但是您也可以在工厂包装,或在进行交互时稍微清洁一下方法。 Hopefully this helps. 希望这会有所帮助。

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

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