I. C # connect PostgreSQL
1. To access the PostgreSQL database, you need to download the npgsql. Net Data Provider for PostgreSQL component from the Pgfoundry Web site.
Access url:http://pgfoundry.org/frs/?group_id=1000140 Note: Because Net4.0 is used, Npgsql-2.2.3-net40.zip is downloaded.
2. Unzip the zip file, copy the Npgsql.dll and Mono.Security.dll files to the packages directory in the C # project directory, and add to the references.
3. In the C # file header that needs to use Npgsql, add the following using statement: Using Npgsql;
Second, use
2.1 Connection string
1, in the configuration file configuration method: The configuration file to add the following statement:
<!-- The database IP address, port number, database name, database logon name, password to access. Encountered garbled plus encoding-->
<connectionStrings>
<add name= "Postgre" connectionstring= "PORT=5432;DATABASE=DEMO; Host=localhost; Password=root; USER id=postgres "/>
</connectionStrings>
Get the connection string in the configuration file in code: string connstr =configurationmanager.connectionstrings["Postgre"]. ToString ();
2, methods configured in code:
String constr = @ "Port=5432;database=demo; Host=localhost; Password=root; USER id=postgres ";
2.2 Establish connection
npgsqlconnection sqlconn = new Npgsqlconnection (CONSTR);
2.3 use DataAdapter query to return a dataset
public DataSet ExecuteQuery (string Span style= "COLOR: #000000" > Sqrstr) {DataSet ds = new DataSet (); try { using (npgsqldataadapter sqldap = new Npgsqldataadapter (Sqrstr, sqlconn)) {Sqldap. Fill (DS); return DS; catch (System.Exception ex) {CloseConnection (); }}
2.4 Adding and pruning operations
Public intExecuteNonQuery (stringsqrstr) { Try{sqlconn.open (); using(Npgsqlcommand SqlCommand =NewNpgsqlcommand (Sqrstr, sqlconn)) { intR = SqlCommand.ExecuteNonQuery ();//executes the query and returns the number of rows affectedSqlconn.close (); returnR//R If the >0 operation is successful! } } Catch(System.Exception ex) {closeconnection (); return 0; } }
View Code
2.5 Back to DataReader query
PublicDbDataReader ExecuteReader (CommandType cmdtype,stringCmdtext) {Sqlconn.open (); Try { using(Npgsqlcommand cmd =NewNpgsqlcommand (cmdtext);) {Npgsqldatareader SDR=cmd. ExecuteReader (commandbehavior.closeconnection); returnSDR; } } Catch{closeconnection (); return NULL; } }
View Code
Using PostgreSQL in C #