Home > database >  WPF app inserting into multiple tables throws an error
WPF app inserting into multiple tables throws an error

Time:09-28

I'm trying to insert data into two tables via a WPF app with a button that saves the data, but I keep getting this error and I need some help. I've tried many videos, try to change the tables in the database but I can't get it to work but it works on the Viestit table, but not on Viestihistoria. The error is

System.Data.SqlClient.SqlException: 'Incorrect syntax near '@Viestinlahettaja'

Thank you in advance.

SqlConnection conn = new SqlConnection(@"Data Source=MYCOMPUTER\SQLEXPRESS;Initial Catalog=LomakeDB;User ID=***;Password=***");
conn.Open();

SqlCommand cmd1 = new SqlCommand("INSERT INTO Viestit(ID,Kokonimi,Viesti,Viestin_saaja) values(@ID,@Kokonimi,@Viesti,@Viestin_saaja)", conn);

cmd1.Parameters.AddWithValue("@ID", txtbox_ID.Text);
cmd1.Parameters.AddWithValue("@Kokonimi",txtbox_Nimi.Text);
cmd1.Parameters.AddWithValue("@Viesti", txtbox_Viesti.Text);
cmd1.Parameters.AddWithValue("@Viestin_saaja", txtbox_Viestinvastaanottaja.Text);

cmd1.ExecuteNonQuery();

cmd1.Parameters.Clear();

SqlCommand cmd2 = new SqlCommand("INSERT INTO Viestihistoria(ViestiID,Viesti,Viestin_lahettaja) values(@ViestiID,@Viesti2,@Viestinlahettaja", conn);

cmd2.Parameters.AddWithValue("@ViestiID", txtbox_ID.Text);
cmd2.Parameters.AddWithValue("@Viesti2", txtbox_Viesti.Text);
cmd2.Parameters.AddWithValue("@Viestinlahettaja", txtbox_Nimi.Text);

cmd2.ExecuteNonQuery();

cmd2.Parameters.Clear();

MessageBox.Show("Data lähetetty onnistuneesti!");
conn.Close();

CodePudding user response:

You forgot to add closing ) at the end of this line in sql command text:

The corrected line:

SqlCommand cmd2 = new SqlCommand("INSERT INTO Viestihistoria(ViestiID,Viesti,Viestin_lahettaja) values(@ViestiID,@Viesti2,@Viestinlahettaja)", conn);
  • Related