Reputation: 13
I want to insert records in my database with asp.net, but it is not really working out well. The data types of the colums in my database are all varchars, except for the randomID. But I still get this error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'Inserted text is here'.'
This is my code
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");
}
}
Upvotes: 0
Views: 973
Reputation: 536
Like the comment says, you should parameterise your query to avoid SQL injection, and also in case one the strings the user has typed in contains a special character (escape character or quote).
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");
}
Upvotes: 2
Reputation: 300
You Missed Comma(,) in insert Query.
Your Code,
cmd.CommandText = " insert into Gebruiker values('" + RandomID + "', '" + Voornaamtxt.Text + "', '" + Tussenvoegseltxt.Text + "', '" + Achternaamtxt.Text + "','" + Emailtxt.Text + "'(here) '" + Niveautxt.Text + "' )";
so try this,
cmd.CommandText = " insert into Gebruiker values('" + RandomID + "', '" + Voornaamtxt.Text + "', '" + Tussenvoegseltxt.Text + "', '" + Achternaamtxt.Text + "','" + Emailtxt.Text + "','" + Niveautxt.Text + "' )";
Upvotes: -1