First of all, you need to use the ExecuteNonQuery method, not the ExecuteReader , since you are executing an INSERT , not a SELECT . So something like:
NpgsqlCommand cmd = new NpgsqlCommand("insert into table1 values(1, 1)", conn); cmd.ExecuteNonQuery();
The ExecuteNonQuery method ExecuteNonQuery also return the number of rows affected if this is important to you.
Secondly, you need to use SQL parameters, and not build an insecure SQL string.
Using:
cmd.Parameters.Add(new NpgsqlParameter("name", tb1.Text)); cmd.Parameters.Add(new NpgsqlParameter("pw", tb2.Text));
To add a parameter to your request. Now you can access it in an INSERT statement with :name or :pw , for example:
NpgsqlCommand cmd = new NpgsqlCommand("insert into login (Name, Password) values(:name, :pw)", conn); cmd.ExecuteNonQuery();
Finally, you might be interested in using ORM instead of executing raw SQL statements. I would check the .NET Entity Framework or Active Record Lock , which is built on NHibernate . These libraries will allow you to query, update, create and delete data in your database without writing actual SQL statements. This is a great way to get started, and just your code will be a bit!
source share