H
H
hidden_pingvin2018-04-13 10:24:06
SQL
hidden_pingvin, 2018-04-13 10:24:06

How to pass parameters to a query in an array in C#?

Hello. Connoisseurs, tell me how in C #, by analogy with PHP, to make the transfer of parameters to the sql query an associative array in order to make a universal function? It's very cumbersome in C# without this.
Here is an example in php:

function db_query($query, $params = array(), $options = array())
    {      //Запрос к БД, где query: текст запроса, params: значения полей или параметры
        global $handle;
        $handle = $this->db_connect('forum');
        $resource = $handle->prepare($query, $options);
        $resource->setFetchMode(PDO::FETCH_ASSOC);
        $resource->execute($params);
        return $resource;
    }
function insert($params = array(), $query = 'INSERT INTO user(login, pass, email, status) values(:login, :password, :email, 2)') {          
        $resource = $this->db_query($query, $params);
        return $this->db_last_insert_id();
    }

Here is an example in C#
public int Insert(int id, string name, string desc, int orderStatusChange)
        {
            id = 0;
            int count = 0;
            Models.DTO.Request request = new Models.DTO.Request();
            using (OracleConnection connection = new OracleConnection(Service1.CONNECTION_STRING))
            {
                connection.Open();
                OracleCommand oraCommand = new OracleCommand("INSERT INTO system.request (request_id, request_name, description, request_status_change_id) "
                                                            + " VALUES (request_seq.NEXTVAL, :req_name, :descr, :orderStatusChange);", connection);

                oraCommand.Parameters.Add("req_name", name);
                oraCommand.Parameters.Add("descr", desc);
                oraCommand.Parameters.Add("orderStatusChange", orderStatusChange);
                count = oraCommand.ExecuteNonQuery();
            }
            return count;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
freeExec, 2018-04-13
@hidden_pingvin

You can either through an array of input parameters

public int Insert(params string[] strParams)
{ 
   var id = strParams[0];
   var name = strParams[1];
...
}

Or through a dictionary
public int Insert(Dictionary<string, string> args)
{ 
  foreach(var kv in args)
  {
      oraCommand.Parameters.Add(kv.Key, kv.Value);
  }
...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question