Reputation:
I am trying to insert basic data into my MSSQL database but I keep receiving this error:
System.Data.SqlClient.SqlException: 'Invalid column name 'Common'.
Invalid column name 'Bug'.
Invalid column name 'sac'.
Invalid column name 'sacas'.'
My query string is:
string query = "INSERT INTO dbo.RNMCommits ([Function], Date, Severity, ChangedBy, Changes)";
query += string.Format(" VALUES ({0}, {1}, {2}, {3}, {4})", function, date, severity, changedBy, changes);
I do not understand the exception, it says that column names Common, Bug, sac, sacas
are invalid, but I am not using these as column names. I am stating in the INSERT statement that it should use ([Function], Date, Severity, ChangedBy, Changes)";
and insert VALUES VALUES ({0}, {1}, {2}, {3}, {4})", function, date, severity, changedBy, changes)
which is common, bug, sac and scas.
These values are strings:
string function = comboBoxEdit_Function.SelectedItem.ToString();
string severity = comboBoxEdit_Severity.SelectedItem.ToString();
string changedBy = textEdit_ChangedBy.Text;
string date = dateEdit_Date.Text;
string changes = memoEdit_Changes.Text;
The whole method that gets executed:
private void simpleButton_OK_Click(object sender, EventArgs e)
{
string function = comboBoxEdit_Function.SelectedItem.ToString();
string severity = comboBoxEdit_Severity.SelectedItem.ToString();
string changedBy = textEdit_ChangedBy.Text;
string date = dateEdit_Date.Text;
string changes = memoEdit_Changes.Text;
SqlConnection cnn;
string connectionString = "Data Source=localhost;Initial Catalog=L3T_Project_Assistent;User ID=xx;Password=xx";
cnn = new SqlConnection(connectionString);
cnn.Open();
string query = "INSERT INTO dbo.RNMCommits ([Function], Date, Severity, ChangedBy, Changes)";
query += string.Format(" VALUES ({0}, {1}, {2}, {3}, {4})", function, date, severity, changedBy, changes);
SqlCommand myCommand = new SqlCommand(query, cnn);
myCommand.ExecuteNonQuery();
cnn.Close();
}
Upvotes: 1
Views: 687
Reputation: 10765
When passing varchar/nvarchar/text
values you need to wrap them in single quotes:
string.Format(" VALUES ('{0}', '{1}', '{2}', '{3}', '{4}')"
Upvotes: 3