2017-04-25 39 views
0

我想用asp.net在我的数据库中插入记录,但实际上效果并不好。我的数据库中colums的数据类型都是varchars,除了randomID。但我仍然得到这个错误:无法使用asp.net将记录插入数据库

System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Inserted text is here'.'

这是我的代码

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"); 
    }  
} 
+2

谷歌鲍比表。 *阅读完*后,您会明白为什么不应该使用字符串连接来生成SQL语句。其中一个文本框包含文字“插入文本在这里”,导致无效查询。它可以是'';选择用户名,用户密码; - 而是。这正是SQL注入攻击的工作原理。改用参数化查询。 –

+0

您在emaitxt.text和niveautxt.text之间缺少逗号 –

+0

不要使用'SqlConnection'或其他任何实现[IDisposable]的地方(https://msdn.microsoft.com/zh-cn/library/system.idisposable(v = vs.110).aspx)作为一个字段。相反,使用局部变量,并将其包装在using语句中。 – mason

回答

-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 + "')"; 
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"); 
} 
相关问题