遍历数据库出现异常
请问一下各位高手,小弟写了一个段遍历数据库的代码:
string path = @"D:\a.txt";
FileStream f = new FileStream(path, FileMode.Open);
StreamWriter sw = new StreamWriter(f,Encoding.UTF8);
DateTime t = System.DateTime.Now;
string strConnection = "Data Source=221.208.168.124;User ID=sa;Password=sa@123456";
SqlConnection sqlConnetion = new SqlConnection(strConnection);
string strDbas = "SELECT Name FROM Master..SysDatabases ORDER BY Name";
SqlDataAdapter adpterDtbase = new SqlDataAdapter(strDbas, strConnection);
DataTable dtbase = new DataTable();
adpterDtbase.Fill(dtbase);
sqlConnetion.Close();
try
{
sw.WriteLine("一共有" + dtbase.Rows.Count.ToString() + "数据库 ");
for (int u = 0; u < dtbase.Rows.Count; u++)
{
string sql = "Data Source=221.208.168.124;Initial Catalog=" + dtbase.Rows[u][0].ToString() + ";User ID=sa;Password=sa@123456";
SqlConnection conn = new SqlConnection(sql);
sw.WriteLine("数据库的名称为" + dtbase.Rows[u][0].ToString());
string strSql = "SELECT Name FROM " + dtbase.Rows[u][0].ToString() + "..SysObjects ORDER BY Name";
SqlDataAdapter adpterDt = new SqlDataAdapter(strSql, conn);
DataTable dt = new DataTable();
adpterDt.Fill(dt);
try
{
sw.WriteLine("一共有" + dt.Rows.Count.ToString() );
for (int i = 0; i < dt.Rows.Count; i++)
{
sw.WriteLine("表的名称为" + dt.Rows[i][0].ToString() );
//string strSql1 = "SELECT Name FROM SysColumns WHERE id=Object_Id('" + dt.Rows[i][0].ToString() + "')";
string sqlTable = "select c.name as colna, t.name as typena, c.length as lenna from syscolumns c "
+ "inner join sysobjects o on c.id = o.id and o.xtype = 'u' inner join systypes t on c.xtype = t.xtype "
+ "where o.name = '" + dt.Rows[i][0].ToString() + "'";
SqlDataAdapter adp2 = new SqlDataAdapter(sqlTable, conn);
DataTable dt1 = new DataTable();
try
{
adp2.Fill(dt1);
sw.WriteLine("一共有" + dt1.Rows.Count.ToString() + "列");
sw.WriteLine("列名" + " " + "字段类型" + " " + "字段长度");
for (int j = 0; j < dt1.Rows.Count; j++)
{
sw.WriteLine(dt1.Rows[j][0].ToString() + " " + dt1.Rows[j][1].ToString() + " " + dt1.Rows[j][2].ToString());
Console.Clear();
Console.WriteLine(System.DateTime.Now.ToLocalTime());
}
sw.WriteLine();
sw.WriteLine();
conn.Close();
}
catch (Exception ex1)
{
sw.WriteLine(ex1.Message);
Console.WriteLine(ex1.Message);
}
}
sw.WriteLine();
sw.WriteLine();
}
catch (Exception ex)
{
sw.WriteLine(ex.Message);
Console.WriteLine(ex.Message);
}
}
}
catch (Exception ex2)
{
sw.WriteLine(ex2.Message);
Console.WriteLine(ex2.Message);
}
finally
{
DateTime ed = System.DateTime.Now;
TimeSpan timeout = ed - t;
sw.WriteLine("用时: " + timeout.TotalSeconds.ToString()+"秒");
sw.Close();
f.Close();
Console.WriteLine(timeout.TotalSeconds.ToString() + "秒");
}
strSql = "SELECT Name FROM " + dtbase.Rows[u][0].ToString() + "..SysObjects ORDER BY Name";