我正在向已建立的 Winforms 应用程序添加新表单。
我的表单上有一个 DataGridView 和调用我的 dbAPI DataTable 方法的代码中的相关方法。我用与 dbAPI 类中使用的许多其他代码完全相同的代码编写了该方法,但由于某种原因,它没有初始化连接字符串......
public DataTable getMyTable()
{
//used for populating the DataGridView
SqlCommand _com = new SqlCommand(string.Format("select * from tab.myTable where Country = 'Angola' "), _conn);
_com.CommandTimeout = _command_timeout;
DataSet _ds = new DataSet();
SqlDataAdapter _adapt = new SqlDataAdapter();
try
{
_adapt.SelectCommand = _com;
int i = _adapt.Fill(_ds, "Asset_Transactions");
if (_ds.Tables.Count > 0)
{
return _ds.Tables[0];
}
else
{
return makeErrorTable("GetMyTable", "No Table Returned for myTable");
}
}
catch (Exception e)
{
return makeErrorTable("GetMyTable", e.Message);
}
}
_conn 是一个 SQLConnection 对象。我的连接字符串在 app.config 中...
class dbAPI
{
Utils _utils = new Utils();
//this is the API between the Application Code and the LDB Database
string _ldb_connection_string = (string)dii.Properties.Settings.Default.connLDB; //connection string but with only one \ in settings as it gets converted to \\
int _command_timeout = Convert.ToInt32((string)dii.Properties.Settings.Default.commandTimeOut); //Command time out
SqlConnection _conn = new SqlConnection();
public dbAPI()
{
//constructor
}
#region --------------- Database Connectivity Section
public string openLocalDatabaseConnection()
{
try
{
//try to create the connection
_conn = new SqlConnection(_ldb_connection_string);
_conn.Open();
}
catch (Exception e)
{
return string.Concat("Can't connect to LDB with '", e.Message, "'");
}
return ""; //success
}
public string closeLocalDatabaseConnection()
{
_conn.Close();
_conn.Dispose();
return "";
}
我得到一个空的连接字符串,并抛出“ConnectionString 属性尚未初始化”异常。我不明白,因为我在课堂上还有许多其他方法可以正常工作。有任何想法吗?
谢谢