在C#中連接PostgreSQL數(shù)據(jù)庫(kù),可以使用以下幾種方法:
using Npgsql;
string connString = "Host=myServerAddress;Username=myUsername;Password=myPassword;Database=myDatabase";
using (var conn = new NpgsqlConnection(connString))
{
conn.Open();
// 執(zhí)行SQL查詢或命令
using (var cmd = new NpgsqlCommand("SELECT * FROM myTable", conn))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
}
}
}
首先,使用NuGet包管理器安裝Entity Framework Core和Npgsql.EntityFrameworkCore包:
Install-Package Microsoft.EntityFrameworkCore
Install-Package Npgsql.EntityFrameworkCore.PostgreSQL
然后,定義實(shí)體類和數(shù)據(jù)上下文:
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql("Host=myServerAddress;Username=myUsername;Password=myPassword;Database=myDatabase");
}
public DbSet<MyEntity> MyEntities { get; set; }
}
public class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
最后,使用數(shù)據(jù)上下文執(zhí)行查詢或命令:
using (var dbContext = new MyDbContext())
{
var entities = dbContext.MyEntities.ToList();
foreach (var entity in entities)
{
Console.WriteLine(entity.Name);
}
}
這些是在C#中連接PostgreSQL數(shù)據(jù)庫(kù)的兩種常用方法,您可以根據(jù)項(xiàng)目的需求選擇適合的方法來(lái)操作數(shù)據(jù)庫(kù)。