如何循环通过多个数据库连接跳过连接错误

时间:2013-05-22 13:23:03

标签: c# vb.net visual-studio dataset datasource

我有一个VB.Net程序,可以访问10个数据库,并为每个数据库填充10个不同的数据集。当我们没有任何活动时,程序会在晚上11点自动运行,所以对我来说这不是最快的完成方式。

但是,我遇到的问题是:如果我尝试连接到脱机的数据库(网络中断,VPN隧道关闭等等,程序将无法继续并最终超时。下面是我的代码的快照,每个站点都会重复。

Me.1TableAdapter.Connection.ConnectionString = "Data Source=10.0.1.1;Initial Catalog=cat;Persist Security Info=True;User ID=id;Password=password;Connection Lifetime=0"
Me.2TableAdapter.Connection.ConnectionString = "Data Source=10.0.1.1;Initial Catalog=cat;Persist Security Info=True;User ID=id;Password=password;Connection Lifetime=0"
Me.3TableAdapter.Connection.ConnectionString = "Data Source=10.0.1.1;Initial Catalog=cat;Persist Security Info=True;User ID=id;Password=password;Connection Lifetime=0"

然后我构建一个包含上述信息的HTML表格:

<html>
    <body>
        <table border="1">
            <tr><th>Description</th><th> Location </th></tr>
                <%= From opentime In Me.Dataset.1.AsEnumerable _
                    Select <tr><td>Open Time</td>
                        <td><%= 1.TimeIn.ToString("hh:mm tt") %></td>
                        <td width="50"><%= 1.Name %></td></tr> %>

等...

然后我转到下一个数据库:

Me.1TableAdapter.Connection.ConnectionString = "Data Source=10.0.1.2;Initial Catalog=cat;Persist Security Info=True;User ID=id;Password=password;Connection Lifetime=0"
    Me.2TableAdapter.Connection.ConnectionString = "Data Source=10.0.1.2;Initial Catalog=cat;Persist Security Info=True;User ID=id;Password=password;Connection Lifetime=0"
    Me.3TableAdapter.Connection.ConnectionString = "Data Source=10.0.1.2;Initial Catalog=cat;Persist Security Info=True;User ID=id;Password=password;Connection Lifetime=0"

然后我为该数据库构建表:

<html>
    <body>
        <table border="1">
            <tr><th>Description</th><th> Location </th></tr>
            <%= From opentime In Me.Dataset.1.AsEnumerable _
                Select <tr><td>Open Time</td>
                    <td><%= 1.TimeIn.ToString("hh:mm tt") %></td>
                    <td width="50"><%= 1.Name %></td></tr> %>
发生了什么,如果第一次尝试(Datasource 10.0.1.1)超时,或者无法连接程序不继续,则会出错。如果检测到第一个数据源出错,如何让程序转到下一个数据源?请记住,它需要跳过剩余的表适配器(在本例中为2,对于Data Source 10.0.1.1为3)。

1 个答案:

答案 0 :(得分:1)

对每个数据库连接使用Try / Catch块。

Try
    Me.1TableAdapter.Connection.ConnectionString = "Data Source=10.0.1.1;Initial Catalog=cat;Persist Security Info=True;User ID=id;Password=password;Connection Lifetime=0"
    'your code here to create HTML table'
Catch ex As Exception
End Try