我有以下情景
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
为什么我得到这个,即使我已正确地将连接字符串分配给连接?
答案 0 :(得分: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语句来正确处理连接对象。我希望你不是像连接字符串那样构建你的查询......