我想用asp.net在我的数据库中插入记录,但它确实运行得不好。我的数据库中列的数据类型都是varchars,除了randomID。但我仍然得到这个错误:
System.Data.SqlClient.SqlException:''插入的文本就在这里'附近的语法不正确。'
这是我的代码
public partial class Registratie : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Danesh\Desktop\Workshop\App_Data\Stap1.mdf;Integrated Security=True");
int RandomID = 2;
String Notification = "Uw Identificatienummer is: ";
protected void Page_Load(object sender, EventArgs e)
{
Random rnd = new Random();
RandomID = rnd.Next(1, 10000000);
}
protected void BtnStap1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " insert into Gebruiker values('" + RandomID + "', '" + Voornaamtxt.Text + "', '" + Tussenvoegseltxt.Text + "', '" + Achternaamtxt.Text + "','" + Emailtxt.Text + "' '" + Niveautxt.Text + "' )";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show(RandomID.ToString(), Notification);
Response.Redirect("/Webpages/LoginPage.aspx");
}
}
答案 0 :(得分:2)
与评论一样,您应该参数化您的查询以避免SQL注入,并且如果用户输入的字符串中包含一个特殊字符(转义字符或引号),则应该参数化。
protected void BtnStap1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
var paramsList = new SqlParameter[]
{
new SqlParameter("@p1", RandomID),
new SqlParameter("@p2", Voornaamtxt.Text),
new SqlParameter("@p3", Tussenvoegseltxt.Text),
new SqlParameter("@p4", Achternaamtxt.Text),
new SqlParameter("@p5", string.Join(" ",Emailtxt.Text,Niveautxt.Text),
};
cmd.CommandText = "insert into Gebruiker values(@p1, @p2, @p3, @p4, @p5)";
cmd.Parameters.AddRange(paramsList);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show(RandomID.ToString(), Notification);
Response.Redirect("/Webpages/LoginPage.aspx");
}
答案 1 :(得分:-1)
您在插入查询中错过了逗号(,)。
您的代码,
cmd.CommandText = " insert into Gebruiker values('" + RandomID + "', '" + Voornaamtxt.Text + "', '" + Tussenvoegseltxt.Text + "', '" + Achternaamtxt.Text + "','" + Emailtxt.Text + "'(here) '" + Niveautxt.Text + "' )";
所以试试这个,
cmd.CommandText = " insert into Gebruiker values('" + RandomID + "', '" + Voornaamtxt.Text + "', '" + Tussenvoegseltxt.Text + "', '" + Achternaamtxt.Text + "','" + Emailtxt.Text + "','" + Niveautxt.Text + "' )";