使用C#连接到Mysql数据库 - 需要一些数据集

时间:2010-12-17 14:37:22

标签: c# mysql dataset

修改

我显然不明白如何做到这一点。在提供示例之后,我决定更多地阅读书籍,并尝试用给出的示例来解决这些问题。

谢谢。

编辑结束

我想连接到mySql DB,读取表/行,然后将它们写入控制台。 这段代码是否正确? 我在Visual Studio 2005中得到了数据集错误。

代码不是我的,从网上获取。我只是修改了一下(变量名等)。

如果你有一个很好的教程,请发布链接。 =)

/* 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
        }
    }
}

1 个答案:

答案 0 :(得分:9)

这是一个简单的例子,您应该遵循以纠正方法中的错误:

SQL的东西

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方法

注意我没有显式打开数据库连接 - DataAdpater为我做了这个。

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示例

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