0

How would I select all the items from a table using C# Visual Studio?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace MySQLConnection
{ 
class Program
{
    static void Main(string[] args)
    {

            Console.WriteLine(args[0]);

    }
}
}
Aaron
  • 11,239
  • 18
  • 58
  • 73

2 Answers2

2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;

namespace ConsoleApplication3
{
    class Program
    {
        public static string db = "server=localhost;database=dsc;uid=root;password=";
        static void Main(string[] args)
        {
            try
            {
                MySqlConnection con = new MySqlConnection(db);
                con.Open(); // connection must be openned for command
                MySqlCommand cmd = new MySqlCommand("Select * FROM `tablename`", con);
                MySqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.GetString("id") + ": " + reader.GetString("name") + " - " + reader.GetString("hs"));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: "+ex);
            }
            finally
            {
                con.Close();
            }
        }
    }
}
Glory Raj
  • 17,397
  • 27
  • 100
  • 203
  • 1
    Gives me an error of. The type of namespace name 'MySQLConnection' could not be found. – Aaron Nov 06 '11 at 17:44
  • 1
    @Matthew Take a look at this link on how to add mysql reference http://stackoverflow.com/questions/1102281/how-do-i-add-a-reference-to-the-mysql-connector-for-net... – Glory Raj Nov 06 '11 at 17:50
1
SqlConnection conn = new SqlConnection([connectionstring]);
SqlCommand com1 =  new SqlCommand("Select * from [tablename]",conn);
conn.Open(); //Open the connection
SqlDataReader reader = com1.ExecuteReader();

while(Reader.Read()){ //read each row at a time

console.write(reader["columname"].toString]);
}

conn.Close(); //don't forget to close it after you're done

Does that help?

The connectionstring is a string which depends on the database location. The stuff in brackets in the sqlcommand is a 'select *' which will return all columns.

When you want to write the stuff out, you either give the column name or an integer. If you don't even know how many columns, you can put a loop which breaks when there's an exception thrown.

Haedrian
  • 4,240
  • 2
  • 32
  • 53