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

    }
}
}

2 Answers 2

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();
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Gives me an error of. The type of namespace name 'MySQLConnection' could not be found.
@Matthew Take a look at this link on how to add mysql reference stackoverflow.com/questions/1102281/…...
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.