3

Edit

I clearly do not understand how to do this right. After the examples were provided, I've decided to hit the books a bit more, and try to work it out with the examples given.

Thank you.

End of Edit

I want to connect to my mySql DB, read the table/rows, and write them to the console. Is this code correct? I get the dataset error in Visual Studio 2005.

Code is not mine, got it from the web. I just modified it a little (variable names and such).

If you have a good tutorial to do this, please post the link. =)

/* Performing a SELECT statement using ADO.NET */
#region Using directives

using System;
using System.Data;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;

#endregion

namespace testConnect1
{
    class SqlTest1
    {
        static void Main()
        {
            string connectionString = "server = localhost user id = root  Password = blank  database = test1"; //connection string


            SqlConnection mySqlConnection = new SqlConnection(connectionString);  //creates connection

            string selectString = "Select field01, field02, field03 " + "FROM myDataTable";  //selects fields to be accessed

            SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

            mySqlCommand.CommandText = selectString;

            SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();

            mySqlDataAdapter.SelectCommand = mySqlCommand;

            DataSet test1DataSet = new DataSet();  //creates data set

            mySqlConnection.Open();   // opens connection

            Console.WriteLine("Retrieving rows from the test table");

            string dataTableName = "myDataTable";
            mySqlDataAdapter.Fill(test1DataSet, dataTableName);

            DataTable myDataTable = test1DataSet.Tables[myDataTable];  //i get an error here

            foreach (DataRow myDataRow in myDataTable.Rows)  //iterates over rows in table
            {

                //Console.WriteLine("Field01") = + myDataRow[("field01")];  // i had to comment out this region because also get an error, but this is not my doubt right now
                //Console.WriteLine("Field02") = + myDataRow[("field02")];
                //Console.WriteLine("Field03") = + myDataRow[("field03")];
            }

            mySqlConnection.Close();  //close connection
        }
    }
}
Koopakiller
  • 2,838
  • 3
  • 32
  • 47
Pablo
  • 285
  • 1
  • 2
  • 7

1 Answers1

9

Here's a simple example which you should follow to correct the mistakes in your approach:

SQL stuff

drop table if exists users;
create table users
(
user_id int unsigned not null auto_increment primary key,
username varbinary(32) unique not null
)
engine=innodb;

insert into users (username) values ('f00'),('bar');

C# DataAdapter method

Note I dont explicitly open the db connection - the DataAdpater does that for me.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// addded these
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data;

namespace mysql
{
    class Program
    {
        static void Main(string[] args)
        {
            const string DB_CONN_STR = "Server=127.0.0.1;Uid=foo_dbo;Pwd=pass;Database=foo_db;";

            MySqlConnection cn = new MySqlConnection(DB_CONN_STR);

            try {

                string sqlCmd = "select * from users order by user_id";

                MySqlDataAdapter adr = new MySqlDataAdapter(sqlCmd, cn);
                adr.SelectCommand.CommandType = CommandType.Text;
                DataTable dt = new DataTable();
                adr.Fill(dt); //opens and closes the DB connection automatically !! (fetches from pool)

                foreach (DataRow dr in dt.Rows){
                    Console.WriteLine(string.Format("user_id = {0}", dr["user_id"].ToString()));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{oops - {0}", ex.Message);
            }
            finally
            {
                cn.Dispose(); // return connection to pool
            }
            Console.WriteLine("press any key...");
            Console.ReadKey();
        }
    }
}

C# DataReader example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// addded these
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data;

namespace mysql
{
    class Program
    {
        static void Main(string[] args)
        {
            const string DB_CONN_STR = "Server=127.0.0.1;Uid=foo_dbo;Pwd=pass;Database=foo_db;";

            MySqlConnection cn = new MySqlConnection(DB_CONN_STR);

            try {

                string sqlCmd = "select * from users order by user_id";

                cn.Open(); // have to explicitly open connection (fetches from pool)

                MySqlCommand cmd = new MySqlCommand(sqlCmd, cn);
                cmd.CommandType = CommandType.Text;
                MySqlDataReader rdr = cmd.ExecuteReader();

                while (rdr.Read()){
                    Console.WriteLine(string.Format("user_id = {0}", rdr["user_id"].ToString()));   
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{oops - {0}", ex.Message);
            }
            finally
            {
                cn.Dispose(); // return connection to the pool
            }
            Console.WriteLine("press any key...");
            Console.ReadKey();
        }
    }
}
Jon Black
  • 16,223
  • 5
  • 43
  • 42
  • I'm getting an error about Linq. I'm required to use .Net 2.0, and it seems the code here is not compatible. I've been toying with it, but really can't figure it out. Any hints? (I don't want a straight answer.) – Pablo Dec 17 '10 at 17:29