SqlCeCommand参数不起作用

Abl*_*rab 0 c# sql sql-server-ce

我有一个SQL Server Compact数据库,我正在尝试使用它来插入记录cmd.ExecuteNonQuery().这种方法在另一个项目中运行得非常好,但它现在不起作用.

private void AddNewProfile() {
    try {
        using(SqlCeConnection conn = new SqlCeConnection(Properties.Settings.Default.dbConnectionString)) {
            using(SqlCeCommand cmd = new SqlCeCommand()) {
                cmd.Connection = conn;

                cmd.CommandText = "INSERT INTO Profiles (ProfileName, ProfilePath, ProfileDescription) VALUES ('@name', '@path', '@desc');";
                cmd.Parameters.AddWithValue("@name", SqlDbType.Text).Value = "New Profile";
                cmd.Parameters.AddWithValue("@path", SqlDbType.Text).Value = "C:\\";
                cmd.Parameters.AddWithValue("@desc", SqlDbType.Text).Value = "A blank profile.";

                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }
    }
    catch(Exception ex) {
        MessageBox.Show(ex.Message, "Error");
    }
}
Run Code Online (Sandbox Code Playgroud)

问题来自于参数 - 我几乎从我的其他项目中复制了代码,但它无法正常工作.而不是执行此:

INSERT INTO Profiles (ProfileName, ProfilePath, ProfileDescription) 
VALUES ('New Profile', 'C:\\', 'A blank profile.');
Run Code Online (Sandbox Code Playgroud)

它执行这个:

INSERT INTO Profiles (ProfileName, ProfilePath, ProfileDescription) 
VALUES ('@name', '@path', '@desc');
Run Code Online (Sandbox Code Playgroud)

这里有什么问题?

Jon*_*eet 5

两个问题:

首先,由于引号,您的SQL指定了文字值.它应该是:

INSERT INTO Profiles (ProfileName, ProfilePath, ProfileDescription)
VALUES (@name, @path, @desc)
Run Code Online (Sandbox Code Playgroud)

这样,SQL引用的是参数,而不是值为"@name","@ path"和"@desc"的文字.

(我也删除了不必要的分号.)

其次,调用AddWithValue,但提供类型作为值,然后覆盖值.这是毫无意义和令人困惑的 - 你指定的类型将会丢失.你应该使用:

cmd.Parameters.Add("@name", SqlDbType.Text).Value = "New Profile";
Run Code Online (Sandbox Code Playgroud)

最后,你不需要调用conn.Close()- 它已经在一个using语句中...你可以传递connSqlCeCommand构造函数,使事情稍微简单一点.