Quantcast
Channel: Visual C# forum
Viewing all articles
Browse latest Browse all 31927

Trouble with INSERT INTO in SQL using C#

$
0
0

i am trying to insert records to a database that is stored locally on my pc by using the INSERT INTO statement from SQL.

Here i my insert method:

private void InjectData()
        {
            OleDbConnection conn = new OleDbConnection();
            conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=EmployeeInformation.accdb";

            string fstName  = txtFirstName.Text.Trim();
            string midName  = txtMiddleName.Text.Trim();
            string lstName = txtLastName.Text.Trim();
            string position  = cboPosition.Text.Trim();
            string salary = txtSalary.Text.Trim();
            OleDbCommand cmd = new OleDbCommand(@"INSERT INTO Employees (FirstName, MiddleName, LastName, Position, Salary) VALUES (@FirstName, @MiddleName, @LastName, @Position, @Salary)")
            {
                Connection = conn
            };

            conn.Open();

            if (conn.State == ConnectionState.Open)
            {
                cmd.Parameters.Add("@FirstName", OleDbType.VarChar).Value = fstName;
                cmd.Parameters.Add("@MiddleName", OleDbType.VarChar).Value = midName;
                cmd.Parameters.Add("@LastName", OleDbType.VarChar).Value = lstName;
                cmd.Parameters.Add("@Position", OleDbType.VarChar).Value = position;
                cmd.Parameters.Add("@Salary", OleDbType.VarChar).Value = salary;

                try
                {
                    cmd.ExecuteNonQuery();
                    MessageBox.Show(@"Data Added");
                    conn.Close();
                }
                catch (OleDbException ex)
                {
                    MessageBox.Show(ex.Source + "\n" + ex.Message);
                    conn.Close();
                }
            }
            else
            {
                MessageBox.Show(@"Connection Failed");
            }
        }

When i run the function by clicking on the add button, i get the error.

Microsoft Access Database Engine
Syntax error in INSERT INTO statement.

i can't seem to find any syntactic errors in my command/statement:

INSERT INTO Employees (FirstName, MiddleName, LastName, Position, Salary) VALUES (@FirstName, @MiddleName, @LastName, @Position, @Salary)

Any help would be greatly appreciated


From, Nathaniel Peiffer


Viewing all articles
Browse latest Browse all 31927

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>