将数据插入带有C#Windows表单的NPGSQL/PostgreSQL数据库

发布于 2025-01-22 19:54:01 字数 2575 浏览 0 评论 0原文

我是编程的新手,我正在尝试创建一个小型应用程序作为学校项目。我希望它能够注册和登录用户。我已经弄清楚了如何创建登录部分,但是我被困在注册上。我已经在PGADMIN内部创建了插入功能,并且它可以使用Windows Forms应用程序来使用它。

到目前为止,这是我的代码:

using Npgsql;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProjektV0._0._2
{
    public partial class frmRegister : Form
    {
        public frmRegister()
        {
            InitializeComponent();
        }

        private NpgsqlConnection conn;
        string connstring = String.Format("Server={0}; Port={1};" +
                "User Id = {2}; Password={3};Database={4};",
                "localhost", "5432", "postgres", "23112001", "demo2");
        private NpgsqlCommand cmd;
        private string sql = null;

        private void frmRegister_Load(object sender, EventArgs e)
        {
            conn = new NpgsqlConnection(connstring);
        }

        private void Register_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }


        private void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                conn.Open();
                sql = @"select * from u_insert(:_username,:_password)";
                cmd = new NpgsqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("_username", txtEmail.Text);
                cmd.Parameters.AddWithValue("_password", txtPswrd.Text);
                if ((int)cmd.ExecuteScalar() == 1)
                {
                    conn.Close();
                    MessageBox.Show("Registered successfuly", "Well done", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    txtEmail.Text = txtPswrd.Text = txtConPswrd.Text = null;
                }
            }
            catch (Exception ex)
            {
                conn.Close();
                MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

    }
}

PGADMIN部分:

create function u_insert
(
    _username character varying,
    _password character varying
)returns int as
$$
begin
    insert into tbl_users
    (
        username,
        password
    )values
    (
        _username,
        _password
    );
    if found then
        return 1;-----success-----
    else
        return 0;-----fail-----
    end if;
end
$$
language plpgsql

正如我所说的那样,我的登录部分甚至通过我的程序和所有其他功能(插入,更新)仅在PGADMIN内部起作用。

I am completely new to programming and I am trying to create a small app as a school project. I want it to be able to register and login users. I have already figured out how to create login part, but I am stuck on registration. I have created Insert function inside pgAdmin and it works but I cant make it work with my windows forms app.

This is my code so far:

using Npgsql;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProjektV0._0._2
{
    public partial class frmRegister : Form
    {
        public frmRegister()
        {
            InitializeComponent();
        }

        private NpgsqlConnection conn;
        string connstring = String.Format("Server={0}; Port={1};" +
                "User Id = {2}; Password={3};Database={4};",
                "localhost", "5432", "postgres", "23112001", "demo2");
        private NpgsqlCommand cmd;
        private string sql = null;

        private void frmRegister_Load(object sender, EventArgs e)
        {
            conn = new NpgsqlConnection(connstring);
        }

        private void Register_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }


        private void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                conn.Open();
                sql = @"select * from u_insert(:_username,:_password)";
                cmd = new NpgsqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("_username", txtEmail.Text);
                cmd.Parameters.AddWithValue("_password", txtPswrd.Text);
                if ((int)cmd.ExecuteScalar() == 1)
                {
                    conn.Close();
                    MessageBox.Show("Registered successfuly", "Well done", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    txtEmail.Text = txtPswrd.Text = txtConPswrd.Text = null;
                }
            }
            catch (Exception ex)
            {
                conn.Close();
                MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

    }
}

pgAdmin part:

create function u_insert
(
    _username character varying,
    _password character varying
)returns int as
$
begin
    insert into tbl_users
    (
        username,
        password
    )values
    (
        _username,
        _password
    );
    if found then
        return 1;-----success-----
    else
        return 0;-----fail-----
    end if;
end
$
language plpgsql

As I said my login part work even through my program and all other functions (insert,update) work only inside pgAdmin.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你怎么敢 2025-01-29 19:54:02

为了澄清我的评论...为什么功能/过程?插入物似乎是戏剧性的过度杀伤力。我会在我的表单之外(在某个地方的crud班上)放置这样的东西:

public static int UpdateUser(string UserId, string Password, out string ErrorMessage)
{
    int result = 0;
    ErrorMessage = null;

    NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
    sb.Host = "localhost";
    sb.Port = 5432;
    sb.Username = "postgres";
    sb.Password = "23112001";
    sb.Database = "demo2";

    using (NpgsqlConnection conn = new NpgsqlConnection(sb.ToString()))
    {
        conn.Open();

        string dml = "insert into tbl_users (username, password) values (:USER, :PW)";

        using (NpgsqlCommand cmd = new NpgsqlCommand(dml, conn))
        {
            cmd.Parameters.AddWithValue("USER", UserId);
            cmd.Parameters.AddWithValue("PW", Password);

            try
            {
                result = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
            }
        }
    }

    return result;
}

然后在按钮单击事件中,您可以将其简化为:

private void btnRegister_Click(object sender, EventArgs e)
{
    string error;
    int insertedRows = CrudClass.UpdateUser(txtEmail.Text, txtPassword.Text, out error);

    if (insertedRows == 1)
    {
        MessageBox.Show("Registered successfuly", "Well done", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        txtEmail.Text = txtPswrd.Text = txtConPswrd.Text = null;
    }
    else
    {
        MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

}

To clarify my comment... why the function/procedure? It seems dramatic overkill for an insert. I would put something like this outside of my form (in a CRUD class somewhere):

public static int UpdateUser(string UserId, string Password, out string ErrorMessage)
{
    int result = 0;
    ErrorMessage = null;

    NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
    sb.Host = "localhost";
    sb.Port = 5432;
    sb.Username = "postgres";
    sb.Password = "23112001";
    sb.Database = "demo2";

    using (NpgsqlConnection conn = new NpgsqlConnection(sb.ToString()))
    {
        conn.Open();

        string dml = "insert into tbl_users (username, password) values (:USER, :PW)";

        using (NpgsqlCommand cmd = new NpgsqlCommand(dml, conn))
        {
            cmd.Parameters.AddWithValue("USER", UserId);
            cmd.Parameters.AddWithValue("PW", Password);

            try
            {
                result = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
            }
        }
    }

    return result;
}

And then within the Button Click event you can simplify it to this:

private void btnRegister_Click(object sender, EventArgs e)
{
    string error;
    int insertedRows = CrudClass.UpdateUser(txtEmail.Text, txtPassword.Text, out error);

    if (insertedRows == 1)
    {
        MessageBox.Show("Registered successfuly", "Well done", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        txtEmail.Text = txtPswrd.Text = txtConPswrd.Text = null;
    }
    else
    {
        MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

}
药祭#氼 2025-01-29 19:54:02

连接字符串 postgres无效。它应该为“ host = {0}; port = {1};用户名= {2}; password = {3}; database = {4};“

然后参数占位符应该是@code>@code>,不是: /code>

提示1:阅读正确数据库的文档

,请注意连接字符串无效,打开连接可能会引发错误。在catch部分中,您首先关闭连接,然后显示错误消息。如果关闭连接失败并引发错误,则代码将永远不会执行。

提示2:不要做任何可能在catch部分中丢弃错误的事情。您可以嵌套另一个try..catch

The connection string is invalid for Postgres. It should rather be "Host={0}; Port={1}; Username= {2}; Password={3};Database={4};"

Then the parameter placeholder should be @, not :

Tip 1: read the doc of the proper database

Note that the connection string is invalid, and opening the connection likely throws an error. In the catch section, you start by closing the connection then you display the error message. If closing the connection fails and throws an error, the code after it will never be executed.

Tip 2: don't do anything that can throw an error within a catch section. You can nest another try..catch though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文