2015-01-13 3 views
2

PostgreSQL을 SQL Server 대신 사용할 수 있는지 확인 중이며 PostgreSQL 공용 스키마의 테스트 데이터베이스에 테스트 테이블을 만들고 테스트 테이블에 두 행의 데이터를 추가했습니다. .Postgresql 용 Npgsql을 사용하는 쿼리가 중복 된 결과와 누락 된 테이블 데이터를 표시합니다.

이제 NpgSQL.dll을 사용하여 C# .net에서 간단한 쿼리를 실행하면 중복 결과가 발생하고 모든 테이블 데이터가 표시되지 않습니다. 색인 = 행 수와 열까지의 열을 표시하는 모든 행에 대한 초기 접근 방식에서

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Data; 
using Npgsql; 


namespace PlayingWithPostgres 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // creating the connection string (Server, Port, User id, password, database) 
      string conStr = "Server=127.0.0.1; Port=5432; User Id=postgres; Password=Sada1973; Database=CarsTestDB;"; 
      NpgsqlConnection conn = new NpgsqlConnection(conStr); 
      string comStr = "Select * FROM \"CarsTable\";"; 
      NpgsqlCommand com = new NpgsqlCommand(comStr, conn); 
      NpgsqlDataAdapter ad = new NpgsqlDataAdapter(com); 
      DataTable dt = new DataTable(); 
      Console.WriteLine("Conection to server established successfuly \n"); 
      // check if connection is open or not 
      if(conn != null && conn.State == ConnectionState.Open) 
      { 
       Console.WriteLine("Connection Open"); 
       conn.Close(); 
      } 
      else 
      { 
       conn.Open(); 
      } 

      // Fill data table with data and start reading 
      ad.Fill(dt); 
      NpgsqlDataReader dRead = com.ExecuteReader(); 

      try 
      { 
       Console.WriteLine("Contents of table in database: \n"); 
       while (dRead.Read()) 
       { 
        foreach(DataRow row in dt.Rows) 
        { 
         for (int i = 0; i < dt.Rows.Count; i++) 
         { 
          Console.Write("{0} \t \n", row[i].ToString()); 
         } 
        } 
       } 
      } 
      catch (NpgsqlException ne) 
      { 
       Console.WriteLine("Problem connecting to server, Error details {0}", ne.ToString()); 
      } 
      finally 
      { 
       Console.WriteLine("Closing connections"); 
       dRead.Close(); 
       dRead = null; 
       conn.Close(); 
       conn = null; 
       com.Dispose(); 
       com = null; 
      } 
     } 
    } 
} 

답변

2

중복 콘텐츠의 문제는 While(dRead.Read())와의 데이터 행을 통해 루프를 사용하여 루프에 의해 발생 foreach을 사용하는 테이블 이렇게하면 효과적으로 데이터에 대해 두 번 반복됩니다.

DataReader을 사용하여 레코드를 반복하려면 DataRow 및 DataTable이 필요하지 않지만 현재 레코드의 DataReader 및 DataReader 인덱서의 FieldCount 속성을 사용하십시오. 당신이 Columns.Count

ad.Fill(dt); 
// Not needed 
// NpgsqlDataReader dRead = com.ExecuteReader(); 
foreach(DataRow row in dt.Rows) 
{ 
    for (int i = 0; i < dt.Columns.Count; i++) 
    { 
     Console.Write("{0} \t \n", row[i].ToString()); 
    } 
} 
+0

두 가지 방법으로 모두 테이블 데이터가 표시되었지만 여전히 복제됩니다 (각 레코드가 두 번 표시됨). –

+0

죄송 합니다만 새 코드를 볼 수 있습니다. 물론 위의 두 메서드 중 하나만 사용하면됩니다. – Steve

+0

물론 하나의 방법을 사용했지만 여전히 중복 결과를 얻었습니다. PostgreSQL을 처음 사용하고 SQLServer에서 항상 작업했기 때문에 데이터 테이블과 데이터 판독기를 사용하지만 PostgreSQL 용도를 테스트하는 한 가지 방법으로 쿼리를 실행하는 것입니다. . –

1

: 여기

은 내가 사용하는 코드입니다. 나는 그것이 당신이 원했던 것이 아니라고 믿습니다. 당신은 같은 행마다 모든 열을 표시해야합니다

대신

foreach(DataRow row in dt.Rows) 
{ 
    for (int i = 0; i < dt.Rows.Count; i++) 
    { 
     Console.Write("{0} \t \n", row[i].ToString()); 
    } 
} 

을 사용 :

foreach(DataRow row in dt.Rows) 
{ 
    for (int i = 0; i < row.ItemArray.Length; i++) 
    { 
     Console.Write("{0} \t \n", row.ItemArray[i].ToString()); 
    } 
} 
+0

없음 ItemArray를 사용하면 루프 필요 DataTable을하고 행을 통해 루프를 원하는 대신하는 경우

// Not needed // ad.Fill(dt); NpgsqlDataReader dRead = com.ExecuteReader(); while (dRead.Read()) { for(int i = 0; i < dRead.FieldCount; i++) Console.Write("{0} \t \n", dRead[i].ToString()); } 

은 데이터 테이블 (DT)에 대해 볼 수 있습니다. –

+0

죄송합니다. 행을 의미합니다. 지금 편집되었습니다. – smiech

+0

작동하지만 여전히 중복 결과가 있습니다. –