无法将数据插入mbf数据库
本文关键字:mbf 数据库 插入 数据 | 更新日期: 2023-09-27 18:22:03
在过去的几个小时里,我一直在尝试将数据插入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
}
}
}
}
如果我将连接参数更改为false,就会出现错误,所以这似乎是正确的。
如有任何帮助,我们将不胜感激。
谢谢!
Alex
尝试将此函数用作模板,最大的区别是它在创建命令之前打开连接。我还没有看到它按照你的方式设置。您还应该在for循环之外打开连接,而不是在for循环中。为什么要反复打开和关闭它;前臂应该在内侧"使用"
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();
}
}
}