效果:

WPF连接mysql数据库查询展示数据_mysql

源码

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using MySql.Data.MySqlClient;


namespace WpfApp2
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

private void btnConnect_Click(object sender, EventArgs e)
{
string MyConStr = "Server=localhost;Database=aaa;uid=root;pwd=123456";

MySqlConnection conn = new MySqlConnection(MyConStr);

conn.Open();

if (conn.State == ConnectionState.Open)
{
MessageBox.Show("Connection Opened Successfully");
conn.Close();
}
}

private void Button_Click(object sender, RoutedEventArgs e)
{
DBConnection conn = new DBConnection();
// DataSet dataset = conn.Select();
DataTable dataset = conn.Select();
if (dataset == null)
{
MessageBox.Show("没有数据");
}
Console.WriteLine("结果:" + dataset);
DataGrid1.ItemsSource = dataset.DefaultView;

}
}

class DBConnection
{
private MySqlConnection connection;
private string connectionStr;

public DBConnection()
{
try
{
string MyConStr = "Server=localhost;Database=aaa;uid=root;pwd=123456";
/*connectionStr = ConfigurationManager.ConnectionStrings[MyConStr].ConnectionString;
connection = new MySqlConnection(connectionStr);*/

connection = new MySqlConnection(MyConStr);
}
catch (Exception exception)
{
throw new Exception("DBConnection Constructor:" + exception.Message);
}
}

public DataTable Select()
{
try
{
connection.Open();
/*if (connection != null)
{
connection.Open();
}*/

Console.WriteLine("---开始查询--");
string cmdStr = "Select * from students";
MySqlCommand sqlCmd = new MySqlCommand(cmdStr, connection);
MySqlDataAdapter sda = new MySqlDataAdapter(sqlCmd);

DataTable ds = new DataTable();
sda.Fill(ds);
return ds;
}
catch (Exception exception)
{
throw new Exception("SelectMethod:" + exception.Message);
}
finally
{
connection.Close();
}
}
}
//