How to connect to postgresql and MySQL from C # [closed]

-1

Good evening, how can I connect to a database in MySQL and another in postgresql using C #, some examples or links for reading.

Thanks

    
asked by alfredo.avmb 10.10.2017 в 05:56
source

1 answer

1

The first thing you should evaluate is the provider you need for each case, for example for Mysql you will need to install the connector.

Download Connector / Net

in this way you will not only have the libraries but also you can connect to the db from Server Explorer of the Visual Studio

In the project you could add the reference by means of nuget

MySql.Data nuget

then the code follows the rules of ado.net

using (MySqlConnection conn = new MySqlConnection("<connection string>"))  
{  
    conn.Open();  

    string query = "INSERT INTO NombreTabla (campo1, campo2) VALUES (?param1, ?param2)";  
    MySqlCommand cmd = new MySqlCommand(query, conn);  
    cmd.Parameters.AddWithValue("?param1", TextBox1.Text);  
    cmd.Parameters.AddWithValue("?param2", Convert.ToDateTime(txtFecha.Text));  

    cmd.ExecuteNonQuery();  

} 

If you know something about ado.net it's exactly the same

For postgresql is quite similar, you need the nuget libraries

Npgsql nuget

and then the code

using (var conn = new NpgsqlConnection(connString))
{
    conn.Open();

    string query = "INSERT INTO data (some_field) VALUES (@p)";
    var cmd = new NpgsqlCommand(query, conn)

    cmd.Parameters.AddWithValue("p", "xx");
    cmd.ExecuteNonQuery();

}

the structure is the same, you have complete examples in the documentation

Npgsql Getting Started

    
answered by 10.10.2017 / 07:19
source