C#程序连接到postgres SQL数据库

时间:2017-03-04 12:30:43

标签: c# postgresql visual-studio npgsql

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.OleDb;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data.Common;
using Npgsql;
using NpgsqlTypes;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            string postgresConStr = String.Format("Server=localhost;Port=5432;UserId=ricards;Password=muzika23;Database=proguzd_4;");
            NpgsqlConnection ncon = new NpgsqlConnection(postgresConStr);
            NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM personas", ncon);
            ncon.Open();
            NpgsqlDataReader dr = cmd.ExecuteReader();

            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("ID", typeof(int)));
            dt.Columns.Add(new DataColumn("vards", typeof(string)));
            dt.Columns.Add(new DataColumn("uzvards", typeof(string)));
            dt.Columns.Add(new DataColumn("vecums", typeof(int)));

            DataColumn[] keyColumns = new DataColumn[1];
            keyColumns[0] = dt.Columns["ID"];
            keyColumns[0].AutoIncrement = true;
            dt.PrimaryKey = keyColumns;

            while (dr.Read())
            {
                DataRow row = dt.NewRow();
                row["ID"] = dr["persona_id"];
                row["vards"] = dr["name"];
                row["uzvards"] = dr["uzvards"];
                row["vecums"] = dr["vecums"];
                dt.Rows.Add(row);
            }
            ncon.Close();
            dt.AcceptChanges();
            int izvele;
            do
            {
                Console.WriteLine("1 - Apskatīt tabulas datus");
                Console.WriteLine("2 - Pievienot tabulai datus");
                Console.WriteLine("3 - Labot tabulas datus");
                Console.WriteLine("4 - Dzēst tabulas datus");
                Console.Write("Jūsu izvēle: ");
                izvele = int.Parse(Console.ReadLine());
                switch (izvele)
                {
                    case 1:
                        PrintTable(dt);
                        break;
                    case 2:
                        Console.Write("Ievadiet cilveku skaitu, cik vēlieties pievienot: ");
                        int CilvSk = Convert.ToInt32(Console.ReadLine());
                        for (int i = 0; i < CilvSk; i++)
                        {
                            DataRow drw = dt.NewRow();

                            Console.Write("Ievadiet studenta vārdu: ");
                            string vards = Console.ReadLine();
                            drw["vards"] = vards;

                            Console.Write("Ievadiet uzvārdu: ");
                            string uzvards = Console.ReadLine();
                            drw["uzvards"] = uzvards;

                            Console.Write("Ievadiet vecumu: ");
                            int vecums = int.Parse(Console.ReadLine());
                            drw["vecums"] = vecums;

                            dt.Rows.Add(drw);
                            ApplyToDb(dt, ncon);
                        }

                        break;
                    case 3:
                        Console.WriteLine("Kuru ierakstu vēlaties labot? : ");
                        int numurs = int.Parse(Console.ReadLine());
                        numurs = numurs - 1;
                        Console.WriteLine("Ievadiet jauno vārdu: ");
                        string jaunaisvards = Console.ReadLine();
                        Console.WriteLine("Ievadiet jauno uzvārdu: ");
                        string jaunaisuzvards = Console.ReadLine();
                        Console.WriteLine("Ievadiet jauno vecumu: ");
                        int jaunaisvecums = int.Parse(Console.ReadLine());
                        Console.WriteLine("Vai tiešām vēlaties veikt izmaiņas? (y/n): ");
                        string atbilde = Console.ReadLine(); ;
                        if (atbilde == "y")
                        {
                            dt.Rows[numurs]["Vards"] = jaunaisvards;
                            dt.Rows[numurs]["Uzvards"] = jaunaisuzvards;
                            dt.Rows[numurs]["Vecums"] = jaunaisvecums;
                            ApplyToDb(dt, ncon);
                            Console.WriteLine("Ierakstā veiktās izmaiņas ir sekmīgi izdarītas");
                            break;
                        }
                        else if (atbilde == "n")
                        {
                            Console.WriteLine("Izmaiņas netika ieviestas");
                            break;
                        }

                        break;
                    case 4:
                        Console.Write("Kuru ierakstu vēlaties dzēst? : ");
                        int ierakstsNr = int.Parse(Console.ReadLine());
                        ierakstsNr = ierakstsNr - 1;
                        Console.Write("Vai tiešām vēlaties dzēst šo ierakstu? (y/n): ");
                        string atbilde2 = Console.ReadLine();
                        if (atbilde2 == "y")
                        {
                            dt.Rows[ierakstsNr].Delete();
                            ApplyToDb(dt, ncon);
                            Console.WriteLine("Ieraksts ir veiksmīgi idzēsts");
                            break;
                        }
                        else if (atbilde2 == "n")
                        {
                            Console.WriteLine("Ieraksts netika dzēsts");
                            break;
                        }
                        break;
                    default:
                        break;
                }
            } while (izvele != 0);

        }
        static void PrintTable(DataTable dt)
        {
            foreach (DataColumn dc in dt.Columns)
            {
                Console.Write(dc.ColumnName + "   ");
            }
            Console.WriteLine();
            Console.WriteLine();
            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < dr.ItemArray.Length; i++)
                {

                    Console.Write(dr[i] + "\t");


                }
                Console.WriteLine();
                Console.WriteLine();
            }

        }
        static void ApplyToDb(DataTable dt, NpgsqlConnection ncon)
        {
            foreach (DataRow dro in dt.GetChanges().Rows)
            {

                if (dro.RowState == DataRowState.Added)
                {
                    NpgsqlCommand add = new NpgsqlCommand("INSERT INTO persona (name, uzvards, vecums,persona_id) VALUES(@vards,@uzvards,@vecums,@persona_id)", ncon);
                    add.Parameters.Add(new NpgsqlParameter("@vards", NpgsqlDbType.Varchar));
                    add.Parameters.Add(new NpgsqlParameter("@uzvards", NpgsqlDbType.Varchar));
                    add.Parameters.Add(new NpgsqlParameter("@vecums", NpgsqlDbType.Integer));
                    add.Parameters.Add(new NpgsqlParameter("@persona_id", NpgsqlDbType.Integer));

                    add.Parameters[0].Value = dro[0];
                    add.Parameters[1].Value = dro[1];
                    add.Parameters[2].Value = dro[2];
                    add.Parameters[3].Value = dro[3];
                    ncon.Open();
                    add.ExecuteNonQuery();
                    ncon.Close();

                }
                if (dro.RowState == DataRowState.Modified)
                {
                    NpgsqlCommand update = new NpgsqlCommand("UPDATE persona SET vards=@vards,uzvards=@uzvards, vecums=@vecums WHERE persona_id=persona_id ", ncon);
                    update.Parameters.Add(new NpgsqlParameter("@vards", dro[1]));
                    update.Parameters.Add(new NpgsqlParameter("@uzvards", dro[2]));
                    update.Parameters.Add(new NpgsqlParameter("@vecums", dro[0]));

                    ncon.Open();
                    update.ExecuteNonQuery();
                    ncon.Close();
                }
                if (dro.RowState == DataRowState.Deleted)
                {
                    NpgsqlCommand delete = new NpgsqlCommand("DELETE FROM persona WHERE persona_id=persona_id; ");
                    delete.Parameters.AddWithValue("@persona_id", dro[0, DataRowVersion.Original]);
                    ncon.Open();
                    delete.ExecuteNonQuery();
                    ncon.Close();
                }
                dt.AcceptChanges();

            }

        }
    }
}

我有一个任务,要连接到PostgreSQL数据库并添加,修改,删除,显示其信息。 我必须使用数据表。

这里的事情是,我已将此程序连接到数据库。它显示了信息等(案例1)但是,当我试图添加(案例2),修改(案例3)或删除(案例4)数据时,它显示了这一点 - This code is in ApplyToDb

我不知道该怎么做。我正在使用NpgSql 2.0来处理数据库和程序。

我是否以正确的方式思考?使用此代码,我输入,修改,删除的信息会自动在数据库中更改吗?

请询问您是否需要任何其他信息来帮助我。 我是编程的初学者,我不太清楚要提供什么样的信息。

0 个答案:

没有答案