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

C# 如何在c中从mysql读取和打印数据#,c#,mysql,C#,Mysql,我的问题是,我无法打印mysql数据库表中的所有数据,我只打印了给定表“teacher”的最后一行。有人能帮我找到错误吗 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数据库表中的所有数据,我只打印了给定表“teacher”的最后一行。有人能帮我找到错误吗

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();
        }
    }
}

显然,您的代码将教师表的最后一行值显示在表单的文本字段中。因为您正在循环通过datareader并将值分配给TextField。因此,每次迭代都会覆盖textbox中以前的值。

您的问题是,您在表单的每一行上覆盖Data2Text.text和datatxt.text数据。如果您想查看这些字段中的所有数据,类似这样的操作可以满足您的需要:

data2text.Text=string.Empty;
datatxt.Text=string.Empty;
while(reader.Read())
{
data2text.Text+=$“{reader.GetString(“id”)};”;
datatxt.Text+=$“{reader.GetString(“userId”)};”;
}

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

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

data2txt.Text = reader.GetString("id");
          datatxt.Text = reader.GetString("userId");
或者使用一个变量来存储每个“读取”中的所有数据,然后输出该变量

varexample.Text += reader.GetString("id");
这个代码有效

private void getdata()
{
MySqlConnection connect = new MySqlConnection("SERVER=localhost; user id=root; password=; database=databasename");
MySqlCommand cmd = new MySqlCommand("SELECT ID, name FROM data WHERE ID='" + txtid.Text + "'");
cmd.CommandType = CommandType.Text;
cmd.Connection = connect;
connect.Open();
try
{
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while(dr.Read())
{
txtID.Text = dr.GetString("ID");
txtname.Text = dr.GetString("name");
}
dr.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if(connect.State == ConnectionState.Open)
{
connect.Close();
}
}

您是否在while循环中设置了断点?文本字段将由查询返回的所有值填充,并将在while循环返回时设置为最后一个值。