I just learn how to connect C# and PostgresSQL. I want to INSERT data from tb1(Textbox) and tb2 to database. But I don\'t know how to code My previous code is SELECT from da
First off, you need to use the ExecuteNonQuery
method rather than ExecuteReader
since you're executing an INSERT
rather than a SELECT
statement. So, something like:
NpgsqlCommand cmd = new NpgsqlCommand("insert into table1 values(1, 1)", conn);
cmd.ExecuteNonQuery();
The ExecuteNonQuery
method will also return the number of rows affected if that's important for you.
Second, you need to use SQL parameters rather than building an unsafe SQL string.
Use:
cmd.Parameters.Add(new NpgsqlParameter("name", tb1.Text));
cmd.Parameters.Add(new NpgsqlParameter("pw", tb2.Text));
To add a parameter to your query. You can now refer to it in your INSERT statement with :name
or :pw
, for example:
NpgsqlCommand cmd = new NpgsqlCommand("insert into login (Name, Password) values(:name, :pw)", conn);
cmd.ExecuteNonQuery();
Lastly, you might be interested in using an ORM rather than executing raw SQL statements. I'd check into the .NET Entity Framework or Castle Active Record, which is built on NHibernate. These libraries will allow you to query, update, create and delete data within your database without writing the actual SQL statements involved. It's a great way to get started, and will simply your code quite a bit!