好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#操作PostgreSql数据库

//C#操作PostgreSql数据库

using Npgsql;

using System;

using System.Data;

namespace TestOne

{

    internal class Program

    {

        static void Main(string[] args)

        {

            NpgsqlConnection dc = DataCon.Conn();

            dc.Open();

            NpgsqlDataAdapter da;

            NpgsqlCommand cmd = new NpgsqlCommand();

            string strSql = "";

            strSql = "insert into atest.testone(name,information) values('hdf',row('cc','dd'))";

            cmd.Connection = dc;

            cmd.CommandText = strSql;

            cmd.CommandType = CommandType.Text;

            cmd.ExecuteNonQuery();

            strSql = "select id,name,(information).name infoname,(information).mobile infomobile from atest.testone";

            cmd.CommandText = strSql;

            cmd.CommandType = CommandType.Text;

            da = new NpgsqlDataAdapter(cmd);

            DataSet ds = new DataSet();

            da.Fill(ds);

            using (DataTable dt = ds.Tables[0])

            {

                foreach (DataRow dr in dt.Rows)

                {

                    Console.WriteLine(dr[1].ToString());

                }

            }

            Console.ReadLine();

            //strSql = "delete from atest.testone where name ='hdf'";

            //cmd.CommandText= strSql;

            //cmd.CommandType = CommandType.Text;

            //cmd.ExecuteNonQuery();

            strSql = "select id,name,(information).name infoname,(information).mobile infomobile from atest.testone where (information).name ='a'";

            cmd.CommandText = strSql;

            cmd.CommandType = CommandType.Text;

            da = new NpgsqlDataAdapter(cmd);

            ds = new DataSet();

            da.Fill(ds);

            using(DataTable dt = ds.Tables[0])

            {

                for (int i = 0; i < dt.Columns.Count; i++)

                {

                    Console.Write(dt.Columns[i].ToString() + "   |   ");

                }

                Console.WriteLine();

                foreach (DataRow dr in dt.Rows)

                {

                    for(int i=0;i<dt.Columns.Count;i++)

                    {

                        Console.Write(dr[i].ToString()+"   |   ");

                    }

                    Console.WriteLine();

                }

            }

            Console.ReadLine();

            dc.Close();

        }

    }

    public class DataCon

    {

        public static NpgsqlConnection Conn()

        {

            string conString = "Host=localhost;UserName=auser;Password=123456;Database=test";

            NpgsqlConnection npgsql = new NpgsqlConnection(conString);

            return npgsql;

        }

    }

}


查看更多关于C#操作PostgreSql数据库的详细内容...

  阅读:14次