码迷,mamicode.com
首页 > 数据库 > 详细

c# 连接Mysql数据库

时间:2014-08-10 08:10:40      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:style   os   io   数据   for   ar   cti   new   

using System.Data;

using MySql.Data.MySqlClient;



private MySqlConnection conn;

private DataTable data;

private MySqlDataAdapter da;

private MySqlCommandBuilder cb;

private DataGrid dataGrid;


private void connectBtn_Click(object sender, System.EventArgs e)

{

if (conn != null)

conn.Close();

string connStr = String.Format("server={0};user id={1}; password={2}; port={3}; database=mysql; pooling=false; charset=utf8",

server.Text, userid.Text, password.Text, 3306);


try 

{

conn = new MySqlConnection( connStr );

conn.Open();


GetDatabases();

                MessageBox.Show("连接数据库成功!");

}

catch (MySqlException ex) 

{

MessageBox.Show( "Error connecting to the server: " + ex.Message );

}

}


private void GetDatabases() 

{

MySqlDataReader reader = null;

MySqlCommand cmd = new MySqlCommand("SHOW DATABASES", conn);


try 

{

reader = cmd.ExecuteReader();

databaseList.Items.Clear();

while (reader.Read()) 

{

databaseList.Items.Add( reader.GetString(0) );

}

}

catch (MySqlException ex) 

{

MessageBox.Show("Failed to populate database list: " + ex.Message );

}

finally 

{

if (reader != null) reader.Close();

}

}


private void databaseList_SelectedIndexChanged(object sender, System.EventArgs e)

{

MySqlDataReader reader = null;

conn.ChangeDatabase(databaseList.SelectedItem.ToString());


MySqlCommand cmd = new MySqlCommand("SHOW TABLES", conn);

try 

{

reader = cmd.ExecuteReader();

tables.Items.Clear();

while (reader.Read()) 

{

tables.Items.Add( reader.GetString(0) );

}

}

catch (MySqlException ex) 

{

MessageBox.Show("Failed to populate table list: " + ex.Message );

}

finally 

{

if (reader != null) reader.Close();

}

}


private void tables_SelectedIndexChanged(object sender, System.EventArgs e)

{

data = new DataTable();

da = new MySqlDataAdapter("SELECT * FROM " + tables.SelectedItem.ToString(), conn );

   cb = new MySqlCommandBuilder( da ); // 此处必须有,否则无法更新


da.Fill( data );


dataGrid.DataSource = data;

}


private void updateBtn_Click(object sender, System.EventArgs e)

{

DataTable changes = data.GetChanges();

da.Update( changes );

data.AcceptChanges();

}


c# 连接Mysql数据库,布布扣,bubuko.com

c# 连接Mysql数据库

标签:style   os   io   数据   for   ar   cti   new   

原文地址:http://my.oschina.net/u/582827/blog/299657

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!