我有一个快速的问题,我的连接没有被初始化。
当我调用 create 方法时,我传入了一堆 varname,比如“ABC、XYZ 等”。
在 foreach 的第一遍中,存储过程被正确调用并且一切正常。但在第二遍时,我得到一个“Connectionstring 属性尚未初始化。
我应该将 myConn.open 和 myConn.close 移到循环之外吗?
我的代码:
public bool Create()
{
bool isSuccess = true;
ConnectionStringSettings myConnectionStringSetting = ConfigurationManager.ConnectionStrings[0];
DbProviderFactory dbFactory = DbProviderFactories.GetFactory(myConnectionStringSetting.ProviderName);
DbConnection myConn = dbFactory.CreateConnection();
myConn.ConnectionString = myConnectionStringSetting.ConnectionString;
DataTable myDataTable = new DataTable();
string[] varNamesArray = m_variableNames.Split(',');
foreach (string varName in varNamesArray)
{
string vn = varName.Trim();
//stored procedure
DbCommand myCommand = dbFactory.CreateCommand();
myCommand.CommandText = "s_LockVariables";
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Connection = myConn;
//variables
DbParameter param1 = myCommand.CreateParameter();
param1.ParameterName = "@varName";
param1.DbType = DbType.String;
param1.Value = vn;
myCommand.Parameters.Add(param1);
DbParameter param2 = myCommand.CreateParameter();
param2.ParameterName = "@datasetID";
param2.DbType = DbType.Int32;
param2.Value = m_datasetID;
myCommand.Parameters.Add(param2);
DbParameter param3 = myCommand.CreateParameter();
param3.ParameterName = "@userID";
param3.DbType = DbType.Int32;
param3.Value = m_userID;
myCommand.Parameters.Add(param3);
DbParameter param4 = myCommand.CreateParameter();
param4.ParameterName = "@currentTime";
param4.DbType = DbType.DateTime;
param4.Value = DateTime.Now;
myCommand.Parameters.Add(param4);
try
{
using (myConn)
{
myConn.Open();
myCommand.ExecuteNonQuery();
myConn.Close();
}
}
catch (Exception e)
{
isSuccess = false;
throw new Exception(e.Message);
//TODO: catch data error
return isSuccess;
}
}
return isSuccess;
}