C#探秘系列(九)WPF连接Mysql数据库
两个函数即可搞定:
private void GetData()
{
MySqlConnection connection = new MySqlConnection(myConnectionString);
connection.Open();
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
LoadData();
}
}
private void LoadData()
{
MySqlConnection connection = new MySqlConnection(myConnectionString);
connection.Open();
try
{
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "select * from notes";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
//this.clothesListView.DataContext = ds.Tables[0].DefaultView;
foreach(DataRow r in ds.Tables[0].Rows)
{
string t = r["title"].ToString();
string d = r["date"].ToString();
string i = r["image"].ToString();
//NotesItem是自定义的控件,noteList是listBox
NotesItem noteTemp = new NotesItem(this, t, d, i);
notesList.Items.Add(noteTemp);
}
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
}
}
}
其中myConnectionString是登录的口令:
private String myConnectionString = "Server=localhost;Database=mydatabse;Uid=root;Pwd=password;";