user2364821
user2364821

Reputation: 43

Trouble in executing the SQL query using c#

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);
            }

        }
    }
}

Please help me to resolve this issue.Thanks. I want to execute SQL query using c# and get the results on console.I guess there is some problem with my code.Please review and let me know the inputs.

Upvotes: 0

Views: 441

Answers (2)

Kreshnik
Kreshnik

Reputation: 2831

If you want to print the query data, you should run a command like this:

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

..inside the while loop.

Upvotes: 2

Rowland Shaw
Rowland Shaw

Reputation: 38128

It appears that you're trying to use the SQL Native Client (normally for use for connecting to Microsoft SQL Server) rather than using an Oracle client. Whilst the System.Data.OracleClient namespace does exist, it is deprecated. Instead, you may want to consider connecting using an OleDbConnection with the appropriate connection string, so something like:

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);
}

Upvotes: 0

Related Questions