1

I wrote a SQL command to save some items in my database. But when I run it, it gives an error message:

enter image description here

And here is my code:

public void Opslaan(string titel, string rVoornaam, string rAchternaam, decimal beoordeling, string a1Voornaam, string a1Achternaam, string a2Voornaam, string a2Achternaam, string a3Voornaam, string a3Achternaam)
    {
        if (beoordelingBest < beoordeling)
        {
            titelBest = titel;
            beoordelingBest = beoordeling;
        }
        string queryString = "INSERT INTO Films (titel, beoordeling) VALUES('" + titel + "', " + beoordeling + ");" +
                             "INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a1Voornaam + "' , '" + a1Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
                             "INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a2Voornaam + "' , '" + a2Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
                             "INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a3Voornaam + "' , '" + a3Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
                             "INSERT INTO Regisseurs (voornaam, achternaam, FilmID) VALUES('" + rVoornaam + "' , '" + rAchternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));";
        command = new SqlCommand(queryString, con);

Can someone please help me with this? I can't figure it out.

jarlh
  • 42,561
  • 8
  • 45
  • 63

3 Answers3

3
  1. Use parametererized queries and do not use string concatination. This is to prevent sql injection attacks but also errors with the values like forgetting to make sure strins are escaped (if a string contains a ' for example).
  2. If you have multiple queries each unique parameter value should have its own parameter name/value
  3. Wrap your ado.net database types (SqlConnection, SqlCommand, etc) in using blocks if they are disposable
  4. Never reuse connections as global objects, create, use, and destroy them when needed.

Here is the updated code with 1 statement, you can append additional statements to this and add more parameters as necessary.

var query = "INSERT INTO Acteurs (voornaam, achternaam, FilmID) SELECT @a1Voornaam, @a1Achternaam, FilmID from Films WHERE titel = @title";

using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(queryString, con))
{
  command.Parameters.Add(new SqlParameter("@a1Voornaam", SqlDbType.VarChar){Value = a1Voornaam});
  command.Parameters.Add(new SqlParameter("@achternaam", SqlDbType.VarChar){Value = achternaam});
  command.Parameters.Add(new SqlParameter("@title", SqlDbType.VarChar){Value = title});

  con.Open();
  command.ExecuteNonQuery();
}
Graham
  • 7,431
  • 18
  • 59
  • 84
Igor
  • 60,821
  • 10
  • 100
  • 175
  • @TimHellegers - be sure to use the proper parameter types too (`SqlDbType` enumeration). As an example, if you are using nvarchar instead of varchar in the database then specify that instead. – Igor Jan 24 '17 at 10:10
  • 1
    Thanks, I tried it with your code above. It worked! Now I'll try to apply this for the other query's – Tim Hellegers Jan 24 '17 at 10:16
  • 1
    This is good, but there's still room for improvement -- if you don't specify the parameter size explicitly, it will be inferred from the value length. If that length differs per query (as you'd expect) it leads to [plan cache pollution](https://blogs.msdn.microsoft.com/ivandonev/plan-cache-pollution-or-how-important-it-is-to-properly-define-parameters-in-code/). To avoid this, specify the size explicitly. – Jeroen Mostert Jan 24 '17 at 11:20
0

Perhaps one of your values is ');

That would terminate the INSERT statement early, and cause the error.

                                                   |
                                                   V
  INSERT INTO Films (titel, beoordeling) VALUES('');,'anything');

You should use SqlParameters instead of string concatenation.

0

Are you using TextBoxes? I can't tell for sure. Try something like this, and change to suit your specific needs.

using System.Data.SqlClient;

protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.
ConfigurationManager.ConnectionStrings["con"].ToString());
    try
    {
        string query = "insert into UserDetail(Name,Address) 
        values('" + txtName.Text + "','" + txtAddress.Text + "');";
        SqlDataAdapter da = new SqlDataAdapter(query, con);
        con.Open();
        da.SelectCommand.ExecuteNonQuery();
        con.Close();
        lblmessage.Text = "Data saved successfully.";
    }
    catch
    {
        con.Close();
        lblmessage.Text = "Error while saving data.";
    }

}
ASH
  • 20,759
  • 19
  • 87
  • 200