如何在C#中从mysql读取和打印数据 [英] How to read and print out data from mysql in c#

查看:242
本文介绍了如何在C#中从mysql读取和打印数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我无法从mysql数据库中的表中打印出所有数据,我仅得到给定表"teacher"中的最后一行.有没有人可以帮助我找到错误?

My problem is that I can't print out all the data from the table in my mysql database, I got out just last row in the given table "teacher". is there anyone who can help me find the error?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace ReadDataFromMysql
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string sql = " SELECT * FROM teacher  ";
            MySqlConnection con = new MySqlConnection("host=localhost;user=root;password=859694;database=projekt;");
            MySqlCommand cmd = new MySqlCommand(sql, con);

            con.Open();

           MySqlDataReader  reader = cmd.ExecuteReader();

           while (reader.Read()) {
               data2txt.Text = reader.GetString("id");
              datatxt.Text = reader.GetString("userId");
           }

        }

        private void btnclose_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}

推荐答案

您的问题是您要覆盖每行数据上的data2txt.Text和datatxt.Text.如果您想查看这些字段中的所有数据,则应执行以下操作:

Your problem is that you are overwriting data2txt.Text and datatxt.Text on each row of data. if you want to see all of the data in those fields, something like this should do what you need:

data2txt.Text = string.Empty;
datatxt.Text = string.Empty;

while (reader.Read())
{
    data2txt.Text += $"{reader.GetString("id")};";
    datatxt.Text += $"{reader.GetString("userId")};";
}

这篇关于如何在C#中从mysql读取和打印数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆