gpt4 book ai didi

c# - 数据库/数据网格上的插入和更新语法错误

转载 作者:搜寻专家 更新时间:2023-10-30 23:37:41 26 4
gpt4 key购买 nike

这是我的保存按钮命令。需要帮助才能让它发挥作用,将得到它来为明天的学校项目辩护。谢谢!它用于 Datagridview、access、c#。我使用 2010VS 和 MS Access 2007。

private void save_Click(object sender, EventArgs e)
{

if (adminyes.Checked == true || adminno.Checked == true && textBox1.Text != null && textBox2.Text != null && textBox3.Text != null)
{
admin = "Yes";

if (mode == "a")
{
x = 0;
connect.Close();
connect.ConnectionString = inventorydb;
connect.Open();
sqlcommand.CommandText = "SELECT * FROM Users WHERE Username ='" +textBox2.Text+ "' Or User_ID ='" +textBox1.Text+ "' ";
sqlcommand.Connection = connect;
OleDbDataReader reader = sqlcommand.ExecuteReader();
while (reader.Read())
{
x++;
}

if (x != 0)
{
MessageBox.Show("", "",MessageBoxButtons.OK);
}
else
{
DialogResult res = MessageBox.Show("Are you sure?", "Save User", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

if (DialogResult.Yes == res)
{
connect.Close();
connect.ConnectionString = inventorydb;
connect.Open();
sqlcommand.CommandText = "INSERT INTO Users (User_ID, Username, Password, Admin) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "', '" + textBox3.Text + "', '" + admin + "') ";
sqlcommand.Connection = connect;
reader = sqlcommand.ExecuteReader();
MessageBox.Show("Record(s) Saved", "Sample");
}

reset();
}
}
else if (mode == "e")
{
DialogResult res = MessageBox.Show("Are you sure?", "Update User", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

if (DialogResult.Yes == res)
{
connect.Close();
connect.ConnectionString = inventorydb;
connect.Open();
sqlcommand.CommandText = "UPDATE Users SET User_ID = '" + textBox1.Text + "', Username = '" + textBox2.Text + "', Password = '" + textBox3.Text + "',Admin = '" + admin + "' WHERE SerialID = '" + idholder + "' ";
sqlcommand.Connection = connect;
OleDbDataReader reader = sqlcommand.ExecuteReader();
reader.Read();
MessageBox.Show("Record(s) Updated", "Sample");

}

reset();
}
}
else
{
MessageBox.Show("", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

最佳答案

Password 是 Access 中的保留字。在您的 SQL 查询中将其更改为 [Password]。您应该像这样包装所有的列和表。

虽然这只是一个学校项目,但我会提到一些事情:

您的代码容易受到 SQL 注入(inject)攻击。以下是如何为您的插入方法解决此问题的示例:

sqlcommand.CommandText = "INSERT INTO [Users] ([User_ID], [Username], [Password], [Admin]) VALUES (@user_id, @username, @password, @admin)";
sqlcommand.Connection = connect;
sqlcommand.Parameters.AddWithValue("@user_id", textBox1.Text);
sqlcommand.Parameters.AddWithValue("@username", textBox2.Text);
sqlcommand.Parameters.AddWithValue("@password", textBox3.Text);
sqlcommand.Parameters.AddWithValue("@admin", admin);
reader = sqlcommand.ExecuteReader();

此外,密码不应以明文形式存储。查看密码散列和加盐以及如何正确处理它以获取更多信息。

关于c# - 数据库/数据网格上的插入和更新语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39688685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com