我只是在学习数据库来存储(大量)用户输入数据。SQL Server:“需要开放和可用的连接”
我有下面的代码,检查记录,并选择是否更新或创建新的
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sc1 = @"select count(*) from job1 where report = @report";
SqlCommand check = new SqlCommand(sc1, connection);
check.Parameters.AddWithValue("@report", jname);
// check if the report number already exists, if not make a new table otherwise insert
int test = (int)check.ExecuteScalar();
if (test > 0)
{
jobCardExistingTable(connection);
digCardExistingTable(connection);
//insert into existing table code
}
如果我请使用jobCardExistingTable
或digCardExisting
表,但做工精细。如果我同时使用,我得到的错误
需要开放和可用的连接
我认为第一ExecuteNonQuery
(其中包含在jobCard
和digCard
方法)是做与连接东西 - 我可以保持这一个开放,或者我每次打电话时都必须打开一个新的方法吗?也许我这样做是不对的......每种方法都在数据库中调用一个新表,我应该一次全部调用它们吗?
编辑:问题的一部分是jobCardTable(digCardTable是相同的,只是不同的查询)
public void jobCardNewTable(SqlConnection connection)
{
using (connection)
{
string sc3 = "";
sc3 = @"INSERT INTO job1 (" + pv.jobstring + ") VALUES (" + pv.jobparam + ")";
SqlCommand cmd = new SqlCommand(sc3, connection);
queryParams(cmd, 0);
cmd.ExecuteNonQuery();
}
}
编辑:解决 - 意识到,使用{}部署的连接。把所有的using{}
出来的方法,以及使用单一using{}
涵盖所有的方法调用和它的作品
'jobCardExistingTable'内发生了什么? –
您可以发布jobCardExistingTable和digCardExistingTable中的代码吗? –
编辑,感谢提问,至少现在我意识到一个问题 – ferday