简体   繁体   中英

query string for inserting elements in npgsql

I want to insert data into a row in PostgreSQL from NPGSQL, but there is something wrong with my query string. Can you please suggest modify it?

   public IActionResult Create(string item_name, string item_count, string item_size)
    {
        using var connection = new NpgsqlConnection(connString);
        connection.Open();
        string query = @"INSERT INTO public.""items""(""item_count"",""item_name"",""item_size"")VALUES ('"+item_count+item_count+item_count+"')";
        using var command = new NpgsqlCommand(query, connection);
        int result = command.ExecuteNonQuery();



        if (result < 0)
        {
            return Error();
        }
        return View(nameof(Create));

    }

You can do it in this way. You have forgotten to add "," between the values and also add quotes if the value is string or date.

    public IActionResult Create(string item_name, string item_count, string item_size)
    {
        using var connection = new NpgsqlConnection(connString);
        connection.Open();
        string query =  String.Format(@"INSERT INTO public.""items""(""item_count"",""item_name"",""item_size"")VALUES('{0}','{1}','{2}');" , item_count , item_count ,item_count);
        using var command = new NpgsqlCommand(query, connection);
        int result = command.ExecuteNonQuery();



        if (result < 0)
        {
            return Error();
        }
        return View(nameof(Create));

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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