我在Visual Studio 2010中使用.mdf数据库。当我向表中添加信息时,我收到错误。当我添加前四行时,我没有遇到任何问题。但是当我添加第五行时,我得到了错误。
这是错误:
SqlException未处理
问题是什么?
dataAccess.AddQuestion("Category1", "Question1?", "1");
dataAccess.AddQuestion("Category2", "Question2?", "2");
dataAccess.AddQuestion("Category3", "Question3?", "3");
dataAccess.AddQuestion("Category4", "Question4?", "4");
dataAccess.AddQuestion("Category5", "Question5?", "5");
当我添加第五个问题时,我收到错误。
以下是我如何将信息添加到数据库中的表的方法。
public void AddQuestion(string title, string question, string answer)
{
sqlConnection = new SqlConnection(connectionString);
sqlCommand = new SqlCommand("INSERT INTO QuestionTable VALUES(@Title, @Question, @Answer)", sqlConnection);
try
{
sqlConnection.Open();
sqlCommand.Parameters.Add(new SqlParameter("@Title", title));
sqlCommand.Parameters.Add(new SqlParameter("@Question", question));
sqlCommand.Parameters.Add(new SqlParameter("@Answer", answer));
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
catch (Exception ex)
{
throw(ex);
}
}
答案 0 :(得分:4)
有没有理由不为SQL对象使用方法范围的变量?试着用这个:
public void AddQuestion(string title, string question, string answer)
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (SqlCommand sqlCommand = new SqlCommand("INSERT INTO QuestionTable VALUES(@Title, @Question, @Answer)", sqlConnection))
{
try
{
sqlConnection.Open();
sqlCommand.Parameters.Add(new SqlParameter("@Title", title));
sqlCommand.Parameters.Add(new SqlParameter("@Question", question));
sqlCommand.Parameters.Add(new SqlParameter("@Answer", answer));
sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
throw;
}
}
}
如果您考虑迁移到SQL Server 2008或更高版本,您也可以查看Table-Valued Parameters。
答案 1 :(得分:0)
为什么不使用多个insert语句一次插入多行,因为它们总是限制每个应用程序池连接到数据库的数量,因此您不能一次关闭连接或使用多个插入
答案 2 :(得分:0)
尝试以下代码,您可能需要lock()
private static readonly object Locker = new object();
public void AddQuestion(string title, string question, string answer)
{
lock (Locker)
{
try
{
sqlConnection = new SqlConnection("");
sqlCommand = new SqlCommand("INSERT INTO QuestionTable VALUES(@Title, @Question, @Answer)", sqlConnection);
sqlConnection.Open();
sqlCommand.Parameters.Add(new SqlParameter("@Title", title));
sqlCommand.Parameters.Add(new SqlParameter("@Question", question));
sqlCommand.Parameters.Add(new SqlParameter("@Answer", answer));
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("That is the Error:" ex.ToString()); // post this Text if it doesn't work
throw (ex);
}
}
}
答案 3 :(得分:0)
我发现了问题(错误)!在数据库中我使用的是nvarchar(50),但我需要一个52个字符的字符串。因此我得到了错误。