VB.NET 7中如何动态修改PostgreSQL Table Adapter的连接字符串?
动态修改VB.NET TableAdapter连接字符串的方法
核心思路
TableAdapter内置Connection属性,直接修改该属性的ConnectionString即可实现动态配置,结合配置文件读取就能做到生产环境无需重建代码即可修改数据库连接。
步骤1:在配置文件中存储连接字符串
在项目的App.config(Web项目用Web.config)中添加连接字符串节点,方便后续修改:
<configuration> <connectionStrings> <add name="PostgreSQLConn" connectionString="Server=你的数据库地址;Port=5432;Database=你的数据库名;User Id=账号;Password=密码;" providerName="Npgsql" /> </connectionStrings> </configuration>
步骤2:读取配置并初始化全局适配器
先添加System.Configuration程序集引用,然后在初始化方法中读取配置并给全局适配器设置连接字符串:
Imports System.Configuration Imports Npgsql ' PostgreSQL驱动命名空间 ' 声明全局适配器 Private Shared mhcVAgingAdapter As mhc_V_Aging_TAdapter Private Shared customerVAgingAdapter As customer_V_Aging_TAdapter ' 适配器初始化方法 Public Sub InitTableAdapters() ' 从配置文件读取连接字符串 Dim connStr As String = ConfigurationManager.ConnectionStrings("PostgreSQLConn").ConnectionString ' 初始化第一个适配器并设置连接 mhcVAgingAdapter = New mhc_V_Aging_TAdapter() If mhcVAgingAdapter.Connection Is Nothing Then mhcVAgingAdapter.Connection = New NpgsqlConnection(connStr) Else mhcVAgingAdapter.Connection.ConnectionString = connStr End If ' 初始化第二个适配器并设置连接 customerVAgingAdapter = New customer_V_Aging_TAdapter() If customerVAgingAdapter.Connection Is Nothing Then customerVAgingAdapter.Connection = New NpgsqlConnection(connStr) Else customerVAgingAdapter.Connection.ConnectionString = connStr End If End Sub
步骤3:使用全局适配器
在业务代码中调用初始化后的适配器即可(建议在程序启动时先执行InitTableAdapters):
' 确保适配器已初始化 InitTableAdapters() Dim newestModifyInMHCDB_Str As String Dim newestModifyInMHCDB_Date As DateTime = New DateTime ' 调用适配器方法 newestModifyInMHCDB_Str = mhcVAgingAdapter.GetOldestModifyDate() If (newestModifyInMHCDB_Str IsNot Nothing) Then newestModifyInMHCDB_Date = DateTime.Parse(newestModifyInMHCDB_Str) End If If (customerVAgingAdapter.CountNewerRecords(newestModifyInMHCDB_Date, gWareHouseCode) < 1) Then vb_log_printf(gsPrgName, 1, myName & $": no records in the PostGreSQL vAging table have a modify date greater than [{newestModifyInMHCDB_Date}], our tables are up to date.") Exit Sub End If
注意事项
- 必须给项目添加
System.Configuration程序集引用:右键项目→添加→引用→勾选System.Configuration - 确保已安装PostgreSQL的.NET驱动(Npgsql),否则无法实例化
NpgsqlConnection - 部分设计器生成的TableAdapter默认未实例化
Connection对象,需先新建NpgsqlConnection实例再赋值
内容的提问来源于stack exchange,提问作者theCodingVapistGolfer
相关产品推荐
相关产品推荐

