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));
}
CodePudding user response:
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));
}