2013-06-19 44 views
0
using System; 
using System.Data.SqlClient; 
namespace ConsoleCSharp 
{ 
    /// <summary> 
    /// Summary description for Class1. 
    /// </summary> 
    class DataReader_SQL 
    { 
     /// <summary> 
     /// The main entry point for the application. 
     /// </summary> 
     [STAThread] 
     static void Main(string[] args) 
     { 
      // 
      // TODO: Add code to start application here 
      // 
      try 
      { 
       SqlConnection thisConnection = new SqlConnection(@"Network Library=dbmssocn;Data 

Source=sourcename,1655;database=Oracle;User id=sysadm;Password=password;"); 
       thisConnection.Open(); 
       SqlCommand thisCommand = thisConnection.CreateCommand(); 
       thisCommand.CommandText = "SELECT * FROM SYSADM.PS_RQ_DEFECT_NOTE where ROW_ADDED_OPRID = 'github'"; 
       SqlDataReader thisReader = thisCommand.ExecuteReader(); 
       while (thisReader.Read()) 
       { 
        Console.WriteLine(thisCommand.CommandText); 
        Console.ReadKey(); 
       } 
       thisReader.Close(); 
       thisConnection.Close(); 
      } 
      catch (SqlException e) 
      { 
       Console.WriteLine(e.Message); 
      } 

     } 
    } 
} 

請幫我解決這個問題。謝謝。我想用c#執行SQL查詢並在控制檯上得到結果。我想我的代碼存在一些問題。請檢查並讓我知道輸入。使用c執行SQL查詢時出現問題#

+0

那麼究竟是什麼錯誤呢?你提到你想在控制檯上得到結果。大。你已經有了一個'Console.WriteLine',那麼你認爲你需要怎樣將結果寫到控制檯呢?另外,當你有機會時,請查閱參數化的SQL查詢。你的SQL代碼非常不安全。同時將你的SQL連接包裝在'using'中 – Arran

+0

@Arran實際上,我的代碼在連接結束後立即退出,並且我的SQL查詢沒有執行。 – user2364821

+0

在數據庫上自己運行查詢...'SELECT * FROM SYSADM.PS_RQ_DEFECT_NOTE where ROW_ADDED_OPRID ='github'' ...它是否返回任何內容?調試這個。在'thisReader.Read()'上放置一個斷點...檢查它裏面的內容。檢查它是否有行。我們不能爲你做這件事。 – Arran

回答

2

如果你要打印查詢數據時,你應該像這樣運行命令:

Console.WriteLine(thisReader["ROW_ADDED_OPRID"].ToString()); 

..inside while循環。

+0

感謝您的回覆。實際上,我的代碼沒有執行SQL查詢,只是在連接建立後退出。 – user2364821

+0

這裏是一些sql查詢的一些例子:[akadia.com](http://www.akadia.com/services/dotnet_data_reader.html)只是看到了sql部分..檢查連接字符串,也許它不是正確:試試這個網站,有不同數據庫服務器的連接字符串:[connectionstrings]。(http://www.connectionstrings.com/) – Kreshnik

0

看起來您嘗試使用SQL Native Client(通常用於連接到Microsoft SQL Server)而不是使用Oracle客戶端。命名空間確實存在System.Data.OracleClientit is deprecated。相反,您可能需要考慮使用OleDbConnection與相應的連接字符串進行連接,因此類似於:

using (OleDbConnection con = new OleDbConnection(@"Network Library=dbmssocn;Data Source=sourcename,1655;database=Oracle;User id=sysadm;Password=password;") 
{ 
    con.Open(); 
    using (OleDbCommand cmd = con.CreateCommand()) 
    { 
     cmd.CommandText = "SELECT * FROM SYSADM.PS_RQ_DEFECT_NOTE where ROW_ADDED_OPRID = 'github'"; 

     using(IDataReader thisReader = cmd.ExecuteReader()) 
     { 
      while (thisReader.Read()) 
      { 
       Console.WriteLine(thisReader["fieldname"]); 
       Console.ReadKey(); 
      } 
     } 
    }; 
} 
catch (Exception e) 
{ 
    Console.WriteLine(e.Message); 
}