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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12408693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:09:45  来源:igfitidea点击:

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

c#mysql

提问by Bahaa Ashi

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?

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

回答by AnandPhadke

Obviously your code shows the last row values of teacher table into your text fields on form.Because your are looping throught the datareader and assigning the values to textfiled.So each iteration it will overwright the previous values in textbox.

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

回答by Mike Corcoran

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 和 datatxt.Text 。如果您想查看这些字段中的所有数据,则应该按照您的需要执行以下操作:

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

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

回答by Brian Warshaw

You're assigning the value of each field instead of the value of the existing control's text plus the new value. Add a breakpoint to make sure you're getting multiple rows, but as your code is written, you would only see the result of one row in your form because you're overwriting on each iteration through the loop.

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

回答by David D.

You should output the data before again writing in it:

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

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

Or use a var to store all the data in with each 'read' and then output that var

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

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

回答by Miguel

This code works.

此代码有效。

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