且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

连接到MySQL数据库用C# - 需要一些与数据集

更新时间:2023-02-03 23:07:43

下面是你应该遵循纠正你的方法的错误一个简单的例子:



SQL的东西


$如果不存在用户b $ b
 删除表; 
创建表的用户

的user_id INT无符号NOT NULL的auto_increment主键,
的用户名VARBINARY(32)唯一不为空

发动机= InnoDB的;

INSERT INTO的用户(用户名)VALUES('F00'),('巴');



C#DataAdapter的方法



请注意,我不明确地打开数据库连接 - 在DataAdpater确实对我来说。

 使用系统; 
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;

// addded使用MySql.Data这些
;
使用MySql.Data.MySqlClient;
使用System.Data这;

命名空间的mysql
{
类节目
{
静态无效的主要(字串[] args)
{
常量字符串DB_CONN_STR =服务器= 127.0.0.1; UID = foo_dbo; PWD =传递;数据库= foo_db;;

的MySqlConnection CN =新的MySqlConnection(DB_CONN_STR);

尝试{

串SQLCMD =由USER_ID SELECT * FROM用户命令;

MySqlDataAdapter的ADR =新MySqlDataAdapter的(SQLCMD,CN);
adr.SelectCommand.CommandType = CommandType.Text;
DataTable的DT =新的DataTable();
adr.Fill(DT); //打开并自动关闭数据库连接! (从池中获取)

的foreach(在dt.Rows的DataRow DR){
Console.WriteLine(的String.Format(USER_ID = {0},博士[user_ID的]。的ToString()));
}
}
赶上(异常前)
{
Console.WriteLine({哎呀 - {0},ex.Message);
}
终于
{
cn.Dispose(); //返回连接池
}
Console.WriteLine(按任意键...);
Console.ReadKey();
}
}
}



C#DataReader的例子​​



 使用系统; 
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;

// addded使用MySql.Data这些
;
使用MySql.Data.MySqlClient;
使用System.Data这;

命名空间的mysql
{
类节目
{
静态无效的主要(字串[] args)
{
常量字符串DB_CONN_STR =服务器= 127.0.0.1; UID = foo_dbo; PWD =传递;数据库= foo_db;;

的MySqlConnection CN =新的MySqlConnection(DB_CONN_STR);

尝试{

串SQLCMD =由USER_ID SELECT * FROM用户命令;

cn.Open(); //必须明确地打开连接(从池中获取)

的MySqlCommand CMD =新的MySqlCommand(SQLCMD,CN);
cmd.CommandType = CommandType.Text;
MySqlDataReader将RDR = cmd.ExecuteReader();

,而(rdr.Read()){
Console.WriteLine(的String.Format(USER_ID = {0},RDR [user_ID的]的ToString()));
}
}
赶上(异常前)
{
Console.WriteLine({哎呀 - {0},ex.Message);
}
终于
{
cn.Dispose(); //返回连接池
}
Console.WriteLine(按任意键...);
Console.ReadKey();
}
}
}


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

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