0

我有以下情况

SqlConnection  sqlMdfCon = new SqlConnection();
sqlMdfCon.ConnectionString = "Data Source=" + txtDataSource.Text + ";Initial Catalog=" + txtDatabase.Text + ";Database=" + txtDatabase.Text + ";User ID=" + txtUserID.Text + ";Password=" + txtPassword.Text + ";Integrated Security=False";
if (sqlMdfCon.State == ConnectionState.Closed)
{
    sqlMdfCon.Open();
}
dTable = sqlMdfCon.GetSchema("Tables"); 
 foreach (DataRow DRow in dTable.Rows)
 {

    if (DRow["TABLE_TYPE"].ToString() == "TABLE" || DRow["TABLE_TYPE"].ToString() == "VIEW" || DRow["TABLE_TYPE"].ToString() == "BASE TABLE")
    {
       intPos = DRow["TABLE_NAME"].ToString().LastIndexOf("FilterDatabase");
       lstTables.Items.Add(DRow["TABLE_NAME"]); // Getting error here
    }
 }

以下是例外

ConnectionString property is not initialized

为什么即使我已将连接字符串正确分配给连接,我也会得到这个?

4

1 回答 1

0

尝试这个:

SqlConnection  sqlMdfCon = new SqlConnection(sqlMdfCon.ConnectionString = "Data Source=" +     txtDataSource.Text + ";Initial Catalog=" + txtDatabase.Text + ";Database=" + txtDatabase.Text + ";User ID=" + txtUserID.Text + ";Password=" + txtPassword.Text + ";Integrated Security=False";);
sqlMdfCon.Open();
dTable = sqlMdfCon.GetSchema("Tables");

顺便说一句,我会添加一个 try/finally 语句来正确处理连接对象。而且我希望您不会用与连接字符串相同的方式构建查询...

于 2013-06-12T12:29:20.713 回答