0

在过去的几个小时里,我一直在尝试将数据插入到 sql 数据库中。由于某种原因,我能够连接到数据库,但没有数据插入到数据库中。如果我直接在数据库中运行 sql 语句,它似乎确实有效。因此,我能够得出结论,该陈述是正确的。此外,运行时没有错误。我有以下 c# 代码:

//Neither of these statements seem to work.
string sqlStatement = "INSERT INTO dbo.eventTable (colA, colB, colC, colD, colE, colF, colG, colH, colI) VALUES (@a,@b,@c,@d,@e,@f,@g,@h,@i)";
string altSqlStatement = "INSERT INTO dbo.eventTable (colA, colB, colC, colD, colE, colF, colG, colH, colI) VALUES (@a,@b,@c,@d,@e,@f,@g,@h,@i)";

    foreach (DataRow row in importData.Rows)
    {
        using (SqlConnection conn = new SqlConnection(form1.Properties.Settings.Default.showConnectionString))
        {
            using (SqlCommand insertCommand = new SqlCommand())
            {
                insertCommand.Connection = conn;
                insertCommand.CommandText = sqlStatement;
                insertCommand.CommandType = CommandType.Text;

                insertCommand.Parameters.AddWithValue("@a", row["CUE"].ToString());
                insertCommand.Parameters.AddWithValue("@b", row["HH"].ToString());
                insertCommand.Parameters.AddWithValue("@c", row["MM"].ToString());
                insertCommand.Parameters.AddWithValue("@d", row["SS"].ToString());
                insertCommand.Parameters.AddWithValue("@e", row["FF"].ToString());
                insertCommand.Parameters.AddWithValue("@f", row["ADDR"].ToString());
                insertCommand.Parameters.AddWithValue("@g", row["Event Description"].ToString());
                insertCommand.Parameters.AddWithValue("@h", row["CAL"].ToString());
                insertCommand.Parameters.AddWithValue("@i", row["PFT"].ToString());

                try
                {
                    conn.Open();
                    int _affected = insertCommand.ExecuteNonQuery();
                }
                catch(SqlException e)
                {
                    // do something with the exception

                }
            }
        }
   }

如果我将连接参数更改为错误的值,则会发生错误,因此这似乎是正确的。

任何帮助将不胜感激。

谢谢!

亚历克斯

4

1 回答 1

0

尝试将此函数用作模板,最大的区别在于它是在创建命令之前打开连接。我还没有看到它按照您设置的方式完成。您还真的应该在 for 循环之外打开连接,而不是在 for 循环中。为什么反复打开和关闭它;foreach 应该在内部“使用”中

public void ExecuteQuery(string query, Dictionary<string, object> parameters)
{
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
    conn.Open();

    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = query;

        if (parameters != null)
        {
            foreach (string parameter in parameters.Keys)
            {
                cmd.Parameters.AddWithValue(parameter, parameters[parameter]);
            }
        }

        cmd.ExecuteNonQuery();
    }
}
}
于 2013-07-11T15:38:51.170 回答