c# postgresql增删查改
时间: 2024-08-23 07:01:55 浏览: 73
在 C# 中操作 PostgreSQL 数据库,通常会使用 ADO.NET 或 Entity Framework 这样的 ORM (Object Relational Mapping) 框架。以下是一些基本的数据库操作步骤:
**连接到 PostgreSQL 数据库**:
```csharp
using Npgsql;
string connectionString = "Host=localhost;Username=myuser;Password=mypassword;Database=mydatabase";
NpgsqlConnection connection = new NpgsqlConnection(connectionString);
connection.Open();
```
**插入数据 (Insert)**:
```csharp
string sqlInsert = "INSERT INTO mytable (column1, column2) VALUES (@value1, @value2)";
NpgsqlCommand command = new NpgsqlCommand(sqlInsert, connection);
command.Parameters.AddWithValue("value1", value1);
command.Parameters.AddWithValue("value2", value2);
int rowsAffected = command.ExecuteNonQuery();
```
**查询数据 (Select)**:
```csharp
string sqlQuery = "SELECT * FROM mytable WHERE condition";
NpgsqlCommand selectCommand = new NpgsqlCommand(sqlQuery, connection);
NpgsqlDataReader reader = selectCommand.ExecuteReader();
while(reader.Read())
{
// 读取每一行数据
string data1 = reader.GetString(0);
int data2 = reader.GetInt32(1);
}
reader.Close();
```
**更新数据 (Update)**:
```csharp
string sqlUpdate = "UPDATE mytable SET column1 = @newValue WHERE id = @id";
NpgsqlCommand updateCommand = new NpgsqlCommand(sqlUpdate, connection);
updateCommand.Parameters.AddWithValue("newValue", newValue);
updateCommand.Parameters.AddWithValue("id", id);
int rowsUpdated = updateCommand.ExecuteNonQuery();
```
**删除数据 (Delete)**:
```csharp
string sqlDelete = "DELETE FROM mytable WHERE id = @id";
NpgsqlCommand deleteCommand = new NpgsqlCommand(sqlDelete, connection);
deleteCommand.Parameters.AddWithValue("id", id);
int rowsDeleted = deleteCommand.ExecuteNonQuery();
```
记得在每次操作完成后关闭连接和释放资源。
阅读全文