Connecting PostgreSQL with a VB.NET application involves establishing a data connection using either ODBC or Npgsql. Here's a comprehensive guide:
1. Connecting with ODBC:
- Install ODBC Driver: Download the PostgreSQL ODBC driver from the official website (http://www.postgresql.org/ftp/odbc/versions/msi/). Install the 32-bit driver.
- Create a Connection String:
Define a connection string using the following format:
Dim MyCon As New Odbc.OdbcConnection MyCon.ConnectionString = "Driver={PostgreSQL ANSI};database=database_name;server=127.0.0.1;port=5432;uid=postgres;sslmode=disable;readonly=0;protocol=7.4;User ID=postgres;password=password;"
- Open the Connection:
Open the connection to the PostgreSQL database using the following code:
MyCon.Open() If mCon.State = ConnectionState.Open Then MsgBox("Connected To PostGres", MsgBoxStyle.MsgBoxSetForeground) End If
2. Using Npgsql Library:
- Install Npgsql: Install the Npgsql library using the NuGet Package Manager in Visual Studio. Search for "Npgsql" and install the latest stable version.
- Create a Connection String:
Define a connection string using the following format:
Public cn As NpgsqlConnection Dim cs As String 'ConnectionString cs = "Server=127.0.0.1:5434;Database=extraits;Userid=postgres;Password='********'"
- Open the Connection:
Open the connection to the PostgreSQL database using the following code:
cn = New NpgsqlConnection(cs) Try cn.Open() Catch ex As Exception MsgBox(ex.Message) End Try
- Execute Queries:
Execute SQL queries using NpgsqlCommand and NpgsqlDataReader objects. For example:
Dim sSQL = "SELECT version()" Dim cmd As New NpgsqlCommand(sSQL, cn) Dim dr As NpgsqlDataReader dr = cmd.ExecuteReader() dr.Read() Dim sVersion As String = dr.Item(0) Console.WriteLine("PostgreSQL VERSION: " & sVersion) dr.Close()