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

时间:2012-09-13 14:33:38

标签: c# mysql

我的问题是我无法打印出我的mysql数据库中表格中的所有数据,我在给定表格的最后一行输出了#34;老师"。是否有人可以帮我找到错误?

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

5 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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

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

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

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

答案 4 :(得分:0)

此代码有效。

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