繁体   English   中英

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

[英]How to read and print out data from mysql in c#

我的问题是我无法从 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();
        }
    }
}

你的问题是你在每行数据上覆盖 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")};";
}

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

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

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

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

或者使用 var 将所有数据存储在每次“读​​取”中,然后输出该 var

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM