0
点赞
收藏
分享

微信扫一扫

Prometheus云原生监控笔记

楠蛮鬼影 2024-03-19 阅读 20
wpfmysql

             界面总要管理数据嘛,于是便学习了一下WPF与MySql的基本连接.

            运行结果:

                

         环境配置

        需要下载安装Mysql,网上教程很多,不详说,创建的工程需要下载或者引入相关的包(MySql.Data)

        连接的部分直接看具体的代码即可

        xaml代码(只放置了一个按钮和文本框)

  <Grid>
        <Button x:Name="btnConnect" Content="Connect to MySQL" HorizontalAlignment="Left" Margin="10" Padding="5" VerticalAlignment="Top" Width="120" Height="30" Click="btnConnect_Click"/>
        <TextBox x:Name="txtResult" HorizontalAlignment="Left" Height="200" Margin="10,50,0,0" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Width="480"/>
    </Grid>

        cs代码(这里需要将connectionString中的数据库相关参数替换成你的),查询语句那里需要替换成你的表.

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            string connectionString = "server=localhost;user=root;database=web;port=3306;password=123456"; // 替换为您的数据库连接信息  
            MySqlConnection connection = null;

            try
            {
                connection = new MySqlConnection(connectionString);
                connection.Open();
                txtResult.Text = "Connected to MySQL successfully!\n";

                // 执行查询示例  
                string query = "SELECT * FROM student"; // 替换为您的查询语句和表名  
                MySqlCommand command = new MySqlCommand(query, connection);
                MySqlDataReader reader = command.ExecuteReader();
                StringBuilder sb = new StringBuilder();
                while (reader.Read())
                {

                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        sb.Append(reader[i].ToString());
                        if (i < reader.FieldCount - 1)
                        {
                            sb.Append(", ");
                        }
                    }
                    sb.AppendLine();

                }
                txtResult.Text += sb.ToString();
                reader.Close();
            }
            catch (Exception ex)
            {
                txtResult.Text = "Error: " + ex.Message;//输出错误信息
            }
            finally
            {
                if (connection != null && connection.State == System.Data.ConnectionState.Open)
                {
                    connection.Close();
                }
            }
        }

    }

        

举报

相关推荐

0 条评论