如何在c#中从mysql读取和打印数据

我的问题是我无法从我的mysql数据库中的表中打印出所有数据,我在给定表“老师”的最后一行得到了。 有没有人可以帮我找到错误?

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。 如果你想看到这些字段中的所有数据,这样的东西应该做你需要的:

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

显然,您的代码会将教师表的最后一行值显示在表单上的文本字段中。因为您正在遍历datareader并将值分配给textfiled。因此,每次迭代它将覆盖文本框中的先前值。

您要分配每个字段的值,而不是现有控件文本的值加上新值。 添加一个断点以确保您获得多行,但是在编写代码时,您只能在表单中看到一行的结果,因为您将通过循环覆盖每次迭代。

您应该在再次写入数据之前输出数据:

 data2txt.Text = reader.GetString("id"); datatxt.Text = reader.GetString("userId"); 

或者使用var来存储每个’read’的所有数据,然后输出该var

 varexample.Text += reader.GetString("id");