Подключение к базе данных Mysql с C# - Нужно немного с наборами данных
редактировать
Я явно не понимаю, как это сделать правильно. После того, как примеры были предоставлены, я решил еще поподробнее заняться книгами и попытаться проработать их с приведенными примерами.
Спасибо.
Конец редактирования
Я хочу подключиться к моей БД mySql, прочитать таблицу / строки и записать их в консоль. Этот код правильный? Я получаю ошибку набора данных в 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 ответ
Вот простой пример, которому вы должны следовать, чтобы исправить ошибки в вашем подходе:
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();
}
}
}