1.准备
1.安装 PostgreSQL 数据库服务器
2.安装 Npgsql 驱动程序,每一个解决方案都要提前添加
3.C# 开发环境:Visual Studio
2.连接 PostgreSQL 的步骤
2.1:导入必要的命名空间
using Npgsql;
2.2:创建连接字符串
string connString = "Host = localhost;Port = 5432;Username = postgres;Password = slac1028;Database = mydb;";
2.3:创建 PostgreSQL 连接对象
NpgsqlConnection conn = new NpgsqlConnection(connString);
2.4:打开数据库连接
conn.Open();
2.5:执行数据库操作
string sql = "INSERT INTO weathers VALUES('San Francisco',40,50,0.25,'1994-11-27');";
NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
cmd.ExecuteNonQuery();
2.6:关闭数据库连接
conn.Close();
示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;
namespace pgsql_demo2
{
class Program
{
static void Main(string[] args)
{
string connString = "Host = localhost;Port = 5432;Username = postgres;Password = slac1028;Database = mydb;";
NpgsqlConnection conn = new NpgsqlConnection(connString);
try
{
conn.Open();
string sql = "INSERT INTO weathers VALUES('San Francisco',40,50,0.25,'1994-11-27');";
NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
//cmd.Parameters.AddWithValue("@temp_lo", 40);
//cmd.Parameters.AddWithValue("@temp_hi", 50);
//cmd.Parameters.AddWithValue("@prcp", 0.25);
//cmd.Parameters.AddWithValue("@date", 1994 - 11 - 27);
cmd.ExecuteNonQuery();
Console.WriteLine(" 数据插入成功!");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine("发生错误:" + ex.Message);
}
finally
{
conn.Close();
}
}
}
}
标签:PostgreSQL,string,C#,cmd,System,基础教程,using,conn
From: https://www.cnblogs.com/workbox/p/17817828.html