INSERT data from a text field in Postgres SQL

I just learned how to connect C # and PostgresSQL. I want to INSERT data from tb1 (text field) and tb2 to the database. But I do not know how to encode My previous code is SELECT from the database. this is my code

private void button1_Click(object sender, EventArgs e) { bool blnfound = false; NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=admin123;Database=Login"); conn.Open(); NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM login WHERE name='" + tb1.Text + "' and password = '" + tb2.Text + "'",conn); NpgsqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { blnfound = true; Form2 f5 = new Form2(); f5.Show(); this.Hide(); } if (blnfound == false) { MessageBox.Show("Name or password is incorrect", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); dr.Close(); conn.Close(); } } 

So please help me with the code.

+4
source share
1 answer

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!

+11
source

All Articles