SqlException:无效的列名,即使它不是该列

时间:2019-05-06 12:18:13

标签: c# sql sql-server

我正在尝试将基本数据插入我的MSSQL数据库,但是我一直收到此错误:

System.Data.SqlClient.SqlException: 'Invalid column name 'Common'.
Invalid column name 'Bug'.
Invalid column name 'sac'.
Invalid column name 'sacas'.'

我的查询字符串是:

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);

我不理解该异常,它说列名Common, Bug, sac, sacas无效,但是我没有将它们用作列名。我在INSERT语句中指出它应该使用([Function], Date, Severity, ChangedBy, Changes)";并插入值为VALUES ({0}, {1}, {2}, {3}, {4})", function, date, severity, changedBy, changes)

的值common, bug, sac and scas.

这些值是字符串:

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;

要执行的整个方法:

    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();
}

1 个答案:

答案 0 :(得分:2)

传递varchar/nvarchar/text值时,您需要将它们用单引号引起来:

string.Format(" VALUES ('{0}', '{1}', '{2}', '{3}', '{4}')"