其实跟java使用JDBC差不多 

下载一个Npgsql.dll,然后在项目中添加引用Npgsql。配置连接数据库的参数:

这些参数最好设置为静态变量,可共享数据。

  private static bool dbIsOpen = false;//数据库是否已经打开

private static string server = "服务器地址";

private static string port = "5432";

private static string database = "库名";

private static string username = "用户名";

private static string password = "密码";

private const int MaxPool = 60;         //最大连接数

private const int MinPool = 5;          //最小连接数

private const int Conn_Timeout = 20;    //设置连接等待时间

private const int maxConnectionCount = 30;//设置检测数据库是否已经开启的最多的次数

将获取参数的方法封装起来,返回参数拼接后的字符串

public static string getConnString()

    {

         string str = "Host=" + server + ";Port=" + port + ";Database=" + database

                + ";USER ID=" + username + ";Password=" + password

                + ";pooling=true;"

                + "MaxPoolSize=" + MaxPool + ";"

                + "MinPoolSize=" + MinPool + ";"

                + "CommandTimeout=" + Conn_Timeout;

         return str;

 }

将获取连接封装成一个方法,将参数字符串传进去,将获取到的连接对象返回,与数据库交互的时候要用到。

public static NpgsqlConnection getConn()

    {

            NpgsqlConnection npsqlConn = null;

            try

            {

                npsqlConn = new NpgsqlConnection(getConnString());

            }

            catch (Exception ex)

            {

                

            }

            return npsqlConn;

}

查询方法,我自己建了实体类,里面有下边赋值的四个属性

  public static student queryStudent()

        {

            student s = null;

            NpgsqlConnection conn = null;//获取链接

            NpgsqlDataReader dr = null; 

            try

            {

                conn = getConn();

                conn.Open();

                string sql = "select name,age,gender,no from test ";

                NpgsqlCommand objCommand = new NpgsqlCommand(sql, conn);

                dr = objCommand.ExecuteReader();

                if (dr.Read())

                { //正常情况下只会有一条记录

                    //开始封装数据

                    s = new student();

                    s.Name = dr[0].ToString();

                    s.Age = int.Parse(dr[1].ToString());

                    s.Gender = dr[2].ToString();

                }

            }

            catch (Exception)

            {

                return s;//可以返回自己想打印的异常信息

                throw;

            }

            finally

            {

//用完之后必须要关闭连接

                conn.Close();

            }

            return s;

        }

参考文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。