C#与OpenGauss的交互可以通过多种方式实现,包括使用ODBC驱动、ADO.NET数据提供程序或直接调用OpenGauss的C语言API。以下是一些常见的方法:
using System.Data.Odbc;
string connectionString = "DSN=OpenGaussDSN;UID=username;PWD=password";
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
connection.Open();
// 执行SQL查询或命令
}
using System.Data.SqlClient;
string connectionString = "Server=localhost;Database=mydatabase;User Id=username;Password=password;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// 执行SQL查询或命令
}
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("libpq", EntryPoint = "PQconnectdb")]
private static extern IntPtr PQconnectdb(string conninfo);
[DllImport("libpq", EntryPoint = "PQfinish")]
private static extern void PQfinish(IntPtr conn);
static void Main()
{
string connectionString = "Host=localhost;Port=5432;Database=mydatabase;User Id=username;Password=password;";
IntPtr conn = PQconnectdb(connectionString);
if (PQstatus(conn) == CONNECTION_OK)
{
// 执行SQL查询或命令
Console.WriteLine("Connected to OpenGauss!");
}
else
{
Console.WriteLine("Failed to connect to OpenGauss!");
}
PQfinish(conn);
}
[DllImport("libpq", EntryPoint = "PQstatus")]
private static extern int PQstatus(IntPtr conn);
}
请注意,直接调用C语言API通常更复杂且性能较低,因此在使用ODBC驱动或ADO.NET数据提供程序时通常是更好的选择。