-3

So I'm playing around a little with SQL and C#. I have a .cs file in which I have a method where I'm gonna use a select to get some info from my database.

I think the syntax I'm using is correct (if not please let me know). But I was wondering which is the best way to store the result. Is there a way to store the result in datasets? If not, which is the best type to store the info?

So here goes my code:

SqlConnection con = new SqlConnection();
        con.ConnectionString = (@"Data Source=XXXXXXXXXX.com;Initial Catalog=XXXXXXXXXX;User ID=XXXXXXXX;Password=XXXXXXXX");

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "SELECT * FROM HISTHDR";
        cmd.CommandType = CommandType.Text;

        cmd.Connection = con;

        con.Open();
        int result = cmd.ExecuteNonQuery();
        con.Close();

        return true;

Thanks in advance!

EfrainReyes
  • 1,005
  • 2
  • 21
  • 55
apachecoq
  • 27
  • 1
  • 4
  • 1
    What results? You're effectively storing the amount of rows returned in an integer.. not sure I see a problem here? – Simon Whitehead Jan 09 '14 at 21:50
  • 1
    I think you may want to run through some tutorials because this doesn't really make enough sense to be able to give a proper response – Jonesopolis Jan 09 '14 at 21:51
  • I left the int because I was using a count. But I don't want the count, I want the actual rows of my table so that I can use to them to later store them in a csv file. @Jonesy – apachecoq Jan 09 '14 at 21:55
  • the first answer [here](http://stackoverflow.com/questions/16958155/fill-datatable-from-sql-server-database) shows how to fill a datatable from a query – Jonesopolis Jan 09 '14 at 21:57
  • 1
    Have you googled about it. Well known code for centuries. – L.B Jan 09 '14 at 21:58

1 Answers1

-1

You are executing:

 cmd.ExecuteNonQuery();

That command is (as its name implies is for NON queries) meant for UPDATES/DELETES etc...

You want to do:

using( DbDataReader rdr = cmd.ExecuteReader() )
{
    while ( rdr.Read() )
    {

        // ... get column data here ...//
        string s = (string) rdr["name"];
     }
 }
T McKeown
  • 12,971
  • 1
  • 25
  • 32