数据未使用C#插入MS Access中

问题描述 投票:0回答:1
private void button1_Click(object sender, EventArgs e)
{
    try
    {
        OleDbConnection connection = new OleDbConnection();
        connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Sanket\Desktop\Practice\C# practice\AIChatbot\Db\Login.accdb;Persist Security Info=False;";

        connection.Open();

        string query = "insert into userLogin(username,password)values('" + tuser.Text + "','" + tpassword.Text + "')";
        OleDbCommand cmd = new OleDbCommand(query,connection);

        int a = cmd.ExecuteNonQuery();
        connection.Close();
    }
    catch (Exception c)
    {
        MessageBox.Show("Error"+c);
    }
}

enter image description here

c#
1个回答
0
投票

这里是您当前代码的问题:

  • Password是Access中的保留关键字。您需要将其封闭在方括号
  • 连接字符串以创建SQL查询是众所周知的问题(Sql Injection,正在解析)
  • 应该打开,使用然后处置连接。使用使用声明

从安全性角度来看,另一个弱点是您将密码以纯文本格式存储在数据库中。任何能够复制该文件的人都会知道您的用户密码。搜索how to hash and salt passwords以将它们存储在数据库中


private void button1_Click(object sender, EventArgs e)
{
    try
    {
        using(OleDbConnection connection = new OleDbConnection())
        {
            connection.ConnectionString = @".....";
            connection.Open();
            string query = @"insert into userLogin(username,[password])
                             values(@user, @pass)";
            OleDbCommand cmd = new OleDbCommand(query,connection);
            cmd.Parameters.Add("@user", OleDbType.VarWChar).Value = tuser.Text;
            cmd.Parameters.Add("@pass", OleDbType.VarWChar).Value = tpassword.Text;
            int a = cmd.ExecuteNonQuery();
        }
    }
    catch (Exception c)
    {
        MessageBox.Show("Error"+c);
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.