gpt4 book ai didi

c# - 如何使用 C# 将带反斜杠的字符串插入到表中

转载 作者:行者123 更新时间:2023-12-04 00:11:04 25 4
gpt4 key购买 nike

我是 C# 新手,仍在自学,我来自 Visual FoxPro 编程。我遇到的问题是我想以仅包含计算机目录的形式从文本框中插入一个值。在该字段中,我选择 C:\,当我运行代码时出现错误:Incorrect syntax near 'C:'

包含目录值的字段名称是lblVault,是一个标签对象。

我运行的代码如下所示:

using (SqlConnection connect = new SqlConnection(@"Data Source=(LocalDB)\v11.0;" +
"AttachDbFilename=C:\\Development\\C-Sharp\\LockItUp\\Lockitup.mdf;Integrated Security=True"))
{
string stmt = "INSERT INTO Users(username,password,folderloc,fullname,email,cellphone) " +
"VALUES (" + @txtUsrName.Text + "," + @txtUserPassword.Text + "," + @lblVault.Text + "," +
@txtFullname.Text + "," + @txtEmail.Text + "," + @txtCellPhone.Text + ")";

using (SqlCommand cmd = new SqlCommand(stmt, connect))
{
try
{
connect.Open();
cmd.ExecuteNonQuery();
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
return;
}
}
}

感谢您的帮助!

最佳答案

最简单和最安全的方法(谷歌“SQL 注入(inject)”)是使用参数,即使是 SQL 查询。它不仅会为您格式化字符串,还会使您免于遇到最简单的安全问题。

using (SqlConnection connect = new SqlConnection(@"Data Source=(LocalDB)\v11.0;" +
"AttachDbFilename=C:\\Development\\C-Sharp\\LockItUp\\Lockitup.mdf;Integrated Security=True"))
{
string stmt = "INSERT INTO Users(username,password,folderloc,fullname,email,cellphone) " +
"VALUES (@username,@password,@folderloc,@fullname,@email,@cellphone)";

using (SqlCommand cmd = new SqlCommand(stmt, connect))
{
cmd.Parameters.Add("@username",txtUsrName.Text);
cmd.Parameters.Add("@password", txtUserPassword.Text);
cmd.Parameters.Add("@folderloc",lblVault.Text);
cmd.Parameters.Add("@fullname", txtFullname.Text);
cmd.Parameters.Add("@email",txtEmail.Text)
cmd.Parameters.Add("@cellphone",txtCellPhone.Text);
try
{
connect.Open();
cmd.ExecuteNonQuery();
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
return;
}
}
}

关于c# - 如何使用 C# 将带反斜杠的字符串插入到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35355756/

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