Write data to PostgreSQL using .NET

To write data to a PostgreSQL database using .NET, you can use the Npgsql library, which is a .NET data provider for PostgreSQL. Here’s an example code

using System;
using Npgsql;

class Program
{
    static void Main()
    {
        // Connection string for the PostgreSQL database
        string connString = "Host=your_host;Username=your_user;Password=your_password;Database=your_database";

        // Create a new PostgreSQL connection
        using (NpgsqlConnection conn = new NpgsqlConnection(connString))
        {
            conn.Open();

            // SQL query to insert data
            string query = "INSERT INTO your_table (name, age, email) VALUES (@name, @age, @email)";

            // Create a command object with the query and connection
            using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn))
            {
                // Set parameter values
                cmd.Parameters.AddWithValue("@name", "John Doe");
                cmd.Parameters.AddWithValue("@age", 30);
                cmd.Parameters.AddWithValue("@email", "[email protected]");

                // Execute the query
                int rowsAffected = cmd.ExecuteNonQuery();

                Console.WriteLine($"Rows affected: {rowsAffected}");
            }
        }
    }
}

In this example, replace 'your_host', 'your_user', 'your_password', and 'your_database' with the actual connection details for your PostgreSQL database.

The code establishes a connection to the PostgreSQL database using the specified host, username, password, and database name. It then creates a command object with the SQL query and the connection.

The example sets parameter values for the query using the AddWithValue() method. The @name, @age, and @email are placeholders.

Finally, the query is executed using ExecuteNonQuery(), which returns the number of rows affected by the query. The example prints the number of rows affected to the console.

Make sure to have the Npgsql library installed in your .NET project. You can install it via NuGet Package Manager or through the .NET CLI:

dotnet add package Npgsql

Remember to handle any exceptions that may occur during the database connection or query execution for proper error handling.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Pamai Tech