简体   繁体   中英

How to fix an error in SQL query in a Winforms application

I'm trying to insert data to a table called ansat (vagtplan). I'm currently writing a WinForms application which uses a SQL Server database, but I still get an error and I can't really see in the code where the error is.

I think, that it must be an error with the SQL query, because when I try to insert data to a table pressing a button, then I get following error message:

Incorrect syntax near 'ansatID, Navn, Efternavn, Adresse, Email, Mobilnr'.

Desired result is a message box with 'Saved', which will confirm, that data are inserted to the table ansat(vagtplan). I have gone through the query many times, but I can't really see where the error is located, so my question is: where is the error located? Maybe should the query be formulated in another way? Here is the code:

private void button1_Click(object sender, EventArgs e)
{
   try
    {
        String ConnectionString = @"Data Source=.\SQLEXPRESS01;Initial Catalog=Vagtplan;Integrated Security=True";
        SqlConnection myconnection = new SqlConnection(ConnectionString);
        myconnection.Open();

        SqlCommand AddCommand = myconnection.CreateCommand();
        AddCommand.CommandText = "INSERT INTO ansat(vagtplan) ([ansatID, Navn, Efternavn, Adresse, Email, Mobilnr]) VALUES (@ansatID, @Navn, @Efternavn, @Adresse, @Email, @Mobilnr)";

        AddCommand.Parameters.AddWithValue("@ansatID", textBox8.Text);
        AddCommand.Parameters.AddWithValue("@Navn", textBox1.Text);
        AddCommand.Parameters.AddWithValue("@Efternavn", textBox2.Text);
        AddCommand.Parameters.AddWithValue("@Adresse", textBox3.Text);
        AddCommand.Parameters.AddWithValue("@Email", textBox6.Text);
        AddCommand.Parameters.AddWithValue("@Mobilnr", textBox7.Text);

        AddCommand.ExecuteNonQuery();

        myconnection.Close();
        MessageBox.Show("Saved");
    } 
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

The insert statement is wrong. It should be something like this:

INSERT INTO ansat(ansatID, Navn, Efternavn, Adresse, Email, Mobilnr) 
VALUES(@ansatID, @Navn, @Efternavn, @Adresse, @Email, @Mobilnr)

No need to specify the database as its already mentioned in the connection string.

您可以尝试以下查询:

INSERT INTO vagtplan.dbo.ansat ([ansatID], [Navn], [Efternavn], [Adresse], [Email], [Mobilnr]) values (@ansatID, @Navn, @Efternavn, @Adresse, @Email, @Mobilnr)

The issue is with your command text "INSERT INTO ansat(vagtplan) ( [ansatID, Navn, Efternavn, Adresse, Email, Mobilnr] ) values (@ansatID, @Navn, @Efternavn, @Adresse, @Email, @Mobilnr)";

INSERT statement syntax is: Insert into <tableName>(<column1>,<column2>) Values(<column1Value>,<column2Value>);

  1. Your INSERT statement's table name seems wrong. It seems ansat is schema name and vagtplan is table name, it should be like ansat.vagtplan or [ansat].[vagtplan]
  2. Column names should be like [column1],[column2] . You have added all columns in a single [] ; that's wrong.

Right click the table in SQL Server Management studio and then script, then INSERT into script. This will give you a SQL insert script for inserting into your table. You can use this script as a basis to create your code.

Thanks for all responses :) I havde figured it out and it works now, but another problem has occured. Now I'm trying to insert data to two tables related to each other through Foreign Key. Table dbo.Ansatte has a primary key called ansatID and table dbo.Login_data has a primary key called brugerID and foreign key AnsatID, which reference to primary key ansatID in table dbo.Ansatte. The primary key in both tables are inserted incrementally when the query s running. I have tried to set IDENTITY_INSERT to ON (in ms sql server management studio), but it doesn't help as I still get error message that IDENTITY_INSERT is set to OFF. The problem is, that after running the query, foreign key AnsatID in table dbo.Login_data is still NULL despite the fact that foreign key AnsatID reference to primary key called ansatID in table dbo.Ansatte. Desired result is that foreign key AnsatID in table dbo.Login_data has the same value as primary key ansatID in table dbo.Ansatte. This also shown on the picture below: enter image description here

So, how to value from primary key into the foreign key? Here is my code:

private void button1_Click(object sender, EventArgs e)
    {
        {
            try
            {
                String ConnectionString = @"Data Source=.\SQLEXPRESS01;Initial Catalog=Vagtplan;Integrated Security=True";
                SqlConnection myconnection = new SqlConnection(ConnectionString);
                myconnection.Open();

                SqlCommand AddWorkerCommand = myconnection.CreateCommand();
                AddWorkerCommand.CommandText = "INSERT INTO dbo.Ansatte ([Navn], [Efternavn], [Adresse], [Postnummer], [Bynavn], [Email], [Mobilnr]) VALUES ( @Navn, @Efternavn, @Adresse, @Postnummer, @Bynavn, @Email, @Mobilnr)";

                AddWorkerCommand.Parameters.AddWithValue("@Navn", textBox1.Text);
                AddWorkerCommand.Parameters.AddWithValue("@Efternavn", textBox2.Text);
                AddWorkerCommand.Parameters.AddWithValue("@Adresse", textBox3.Text);
                AddWorkerCommand.Parameters.AddWithValue("@Postnummer", textBox4.Text);
                AddWorkerCommand.Parameters.AddWithValue("@Bynavn", textBox5.Text);
                AddWorkerCommand.Parameters.AddWithValue("@Email", textBox6.Text);
                AddWorkerCommand.Parameters.AddWithValue("@Mobilnr", textBox7.Text);
                AddWorkerCommand.ExecuteNonQuery();

                SqlCommand AddUserCommand = myconnection.CreateCommand();
                AddUserCommand.CommandText = "INSERT INTO dbo.Login_data ([Brugernavn], [Adgangskode], [Brugertype]) VALUES ( @Brugernavn, @Adgangskode, @Brugertype)";

                AddUserCommand.Parameters.AddWithValue("@Brugernavn", textBox10.Text);
                AddUserCommand.Parameters.AddWithValue("@Adgangskode", textBox9.Text);
                AddUserCommand.Parameters.AddWithValue("@Brugertype", textBox8.Text);
                AddUserCommand.ExecuteNonQuery();

                myconnection.Close();
                MessageBox.Show("Saved");
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM