c# 串連Mysql資料庫

來源:互聯網
上載者:User

標籤: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();

}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.