WPF连接MySqldemo

本文介绍了如何在WindowsPresentationFoundation(WPF)应用中使用MySql数据库进行基本连接,包括环境配置、XAML布局和C#代码实现,展示了如何设置连接字符串、执行查询并处理异常。
摘要由CSDN通过智能技术生成

             界面总要管理数据嘛,于是便学习了一下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();
                }
            }
        }

    }

        

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值