无法使用C#更新到.mdb文件

时间:2013-01-21 20:38:28

标签: c# visual-studio ms-access sql-update

起初我试过这个:

    string set = "";
    for (int i = 1; i < result.Count; i++)
    {
        if ((fieldtypes[i] == "System.Int32"))
        {
            set += fields[i] + "=" + result[i] + ", ";
        }
        else if (fieldtypes[i] == "System.String")
        {
            set += fields[i] + "='" + result[i] + "', ";
        }
        else if (fieldtypes[i] == "System.Boolean")
        {
            set += fields[i] + "=" + result[i] + ", ";
        }
        else if (fieldtypes[i] == "System.DateTime")
        {
            set += fields[i] + "='#" + System.DateTime.Now + "#', ";
        }
    }
    set = set.Substring(0, set.Length - 2);
    string sql11 = "UPDATE [Contacts] SET " + set + " WHERE pkContactID=" + cKey;
    OleDbCommand myCommand11 = new OleDbCommand(sql11, myConnection);
    myCommand11.ExecuteNonQuery();

当我省略字符串和日期时间条件以便它只更新int和boolean时,现在这个工作了。因此,当我尝试更新类型为字符串的字段时,它与语法错误有关。


然后我听说在写入.mdb文件时你必须使用参数,所以我尝试了这个:

        string sql11 = "UPDATE [Contacts] SET ";
        for (int i = 1; i < result.Count; i++)
        {
            sql11 += fields[i] + " = ?, ";
        }
        sql11 = sql11.Substring(0, sql11.Length - 2);
        sql11 += " WHERE pkContactID = " + cKey;
        using (myConnection)
        {
            using (OleDbCommand myCommand11 = new OleDbCommand(sql11, myConnection))
            {
                myCommand11.CommandType = CommandType.Text;
                for (int j = 1; j < result.Count; j++)
                {
                    if (fieldtypes[j] == "System.Int32")
                    {
                        myCommand11.Parameters.AddWithValue(fields[j], int.Parse(result[j]));
                    }
                    else if (fieldtypes[j] == "System.String")
                    {
                        myCommand11.Parameters.AddWithValue(fields[j], result[j]);
                    }
                    else if (fieldtypes[j] == "System.Boolean")
                    {
                        myCommand11.Parameters.AddWithValue(fields[j], Boolean.Parse(result[j]));
                    }
                    else if (fieldtypes[j] == "System.DateTime")
                    {
                        myCommand11.Parameters.AddWithValue(fields[j], DateTime.Now);
                    }
                }
                Console.WriteLine(sql11);
                myCommand11.ExecuteNonQuery();
            }
        }
    }

哪个也没用。我不认为?正在被更换。

无论如何,请帮我修复它,以便我能正确更新。

1 个答案:

答案 0 :(得分:0)

我只是创建了一个DataTable对象并选择了我想要更新的行,而不必使用容易出现语法错误的Access的UPDATE查询字符串。然后我通过我想要更改的元素数组更新了表,然后使用适配器将表更新回服务器。这很好,没有我担心语法! :)

干杯