2017-04-25 81 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"); 
} 
相關問題