将数据从文本框插入到 Postgres SQL [英] INSERT data from Textbox to Postgres SQL
问题描述
我刚刚学习了如何连接 C# 和 PostgresSQL.我想将数据从 tb1(Textbox) 和 tb2 插入数据库.但我不知道如何编码我以前的代码是从数据库中选择.这是我的代码
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 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();
}
}
所以请帮我看看代码.
推荐答案
首先,您需要使用 ExecuteNonQuery
方法而不是 ExecuteReader
方法,因为您正在执行一个INSERT
而不是 SELECT
语句.所以,就像:
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();
如果这对您很重要,ExecuteNonQuery
方法还将返回受影响的行数.
The ExecuteNonQuery
method will also return the number of rows affected if that's important for you.
其次,您需要使用 SQL 参数而不是构建不安全的 SQL 字符串.
Second, you need to use SQL parameters rather than building an unsafe SQL string.
使用:
cmd.Parameters.Add(new NpgsqlParameter("name", tb1.Text));
cmd.Parameters.Add(new NpgsqlParameter("pw", tb2.Text));
向您的查询添加参数.您现在可以在 INSERT 语句中使用 :name
或 :pw
引用它,例如:
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();
最后,您可能对使用 ORM 而不是执行原始 SQL 语句感兴趣.我会检查 .NET Entity Framework 或 Castle Active Record,它建立在 NHibernate.这些库将允许您查询、更新、创建和删除数据库中的数据,而无需编写实际涉及的 SQL 语句.这是一个很好的入门方式,而且会让你的代码变得很简单!
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!
这篇关于将数据从文本框插入到 Postgres SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!