我想使用ASP.NET插入数据库中的记录,但它并不是很好。我的数据库中的colums的数据类型都是varchars,除了rantyid。但是我仍然会遇到这个错误:
system.data.sqlclient.sqlexception:'插入文本附近的不正确语法在这里'。'
这是我的代码
public partial class Registratie : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=C:UsersDaneshDesktopWorkshopApp_DataStap1.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");
}
}
就像评论所说的那样,您应该参数查询以避免SQL注入,并且在一个字符串中输入的字符串包含一个特殊字符(逃脱字符或Quote(。/p>
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");
}
您在插入查询中错过了逗号(,(。
您的代码,
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 + "' )";