簡體   English   中英

將數據從Textbox INSERT到Postgres SQL

[英]INSERT data from Textbox to Postgres SQL

我只是學習如何連接C#和PostgresSQL。 我想將數據從tb1(文本框)和tb2插入數據庫。 但我不知道如何編碼我以前的代碼是從數據庫中選擇SELECT。 這是我的代碼

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語句。 所以,像:

NpgsqlCommand cmd = new NpgsqlCommand("insert into table1 values(1, 1)", conn);
cmd.ExecuteNonQuery();

ExecuteNonQuery方法還將返回受影響的行數(如果這對您很重要)。

其次,您需要使用SQL參數而不是構建不安全的SQL字符串。

使用:

cmd.Parameters.Add(new NpgsqlParameter("name", tb1.Text));
cmd.Parameters.Add(new NpgsqlParameter("pw", tb2.Text));

向查詢中添加參數。 您現在可以在INSERT語句中使用:name:pw引用它,例如:

NpgsqlCommand cmd = new NpgsqlCommand("insert into login (Name, Password) values(:name, :pw)", conn);
cmd.ExecuteNonQuery();

最后,您可能對使用ORM而不是執行原始SQL語句感興趣。 我將檢查基於NHibernate構建的.NET Entity FrameworkCastle Active Record 這些庫允許您在數據庫中查詢,更新,創建和刪除數據,而無需編寫所涉及的實際SQL語句。 這是一個很好的入門方式,而且只需要你的代碼!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM