0

我目前正在使用 OleDB 访问数据库,并且遇到了 OleDBParameter 的字符串替换问题。

using (OleDbCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = "SELECT * FROM " + tablename + " WHERE ID = @ID ;";
    cmd.Parameters.AddWithValue("@ID", testslist.number + "_" + testcase.name + "_" + testcase.config);
    OleDbDataReader reader = cmd.ExecuteReader();
    RecordExists = reader.HasRows;
    reader.Close();

    if (RecordExists)
    {
        string updatestring = null;
        foreach (KeyValuePair<string, string> kv in dictionary)
            updatestring = updatestring + kv.Key + " = '@val" + kv.Key + "',";
        cmd.CommandText = "UPDATE " + tablename + " SET " + updatestring.Remove(updatestring.Length - 1) + " WHERE ID = @ID;";

        foreach(KeyValuePair<string,string> kv in dictionary)
        {
            if (kv.Value == null)
                cmd.Parameters.AddWithValue("@val" + kv.Key, DBNull.Value);
            else
                cmd.Parameters.AddWithValue("@val" + kv.Key, kv.Value);
        }
        cmd.ExecuteNonQuery();
    }
    else
    {
        string insertstring = "ID,";
        string valuestring = "@ID,";

        foreach(KeyValuePair<string,string>kv in dictionary)
        {
            insertstring = insertstring + kv.Key + ",";
            valuestring = valuestring + "@var" + kv.Key + ",";
           // valuestring = valuestring + "'"+ kv.Value+ "',";
        }
        cmd.CommandText = "INSERT INTO " + tablename + " (" + insertstring.Remove(insertstring.Length - 1) + ") VALUES(" + valuestring.Remove(valuestring.Length - 1) + ");";
        foreach (KeyValuePair<string, string> kv in dictionary)
        {
            if (kv.Value == null)
                cmd.Parameters.AddWithValue("@val" + kv.Key, DBNull.Value);
            else
                cmd.Parameters.AddWithValue("@val" + kv.Key, kv.Value);
        }
        cmd.ExecuteNonQuery();
}   

无论出于何种原因,只有@ID 在我的数据库中被正确替换。运行代码后,ID 在我的数据库中被正确替换,但所有其他字段值都是 @var[nameofthekey] (例如@varTestCase)。我真的不知道再去哪里看,尤其是因为一个参数在数据库中被正确替换,但另一个参数却没有。

谢谢您的帮助!

编辑:我忘了提,我正在使用访问数据库(accdb)

4

0 回答 0