首页 > 代码库 > c# 连接Mysql数据库

c# 连接Mysql数据库

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 = http://www.mamicode.com/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();

}