1

首先,这是我第一次尝试 C#。我的问题是,无论我使用数据表、列表还是 mysqldatareader;查询只返回一个结果,并且只返回表的最后一个结果。

我的表值是(列名在前):索引城市 1 巴黎 2 伦敦

我的 C# 最后一次代码尝试是:

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;
using MySql.Data.MySqlClient;
namespace MySQL_Sample
{

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }


    private void button1_Click(object sender, EventArgs e)
    {
        //MySql connections
        MySqlConnection connection;
        string host;
        string db;
        string uid;
        string pass;
        host = "localhost";
        db = "sample";
        uid = "root";
        pass = "";
        string ConnectionString = "SERVER=" + host + ";" + "DATABASE=" + db + ";" + "UID=" + uid + ";" + "PASSWORD=" + pass + ";";
        connection = new MySqlConnection(ConnectionString);
        connection.Open();
        //MySql Commands
        string sql = "SELECT * FROM table1";
        MySqlCommand cmd = new MySqlCommand(sql, connection);
        MySqlDataReader rdr = cmd.ExecuteReader();
        //MySql Call back
        while(rdr.Read())
        {
            DataTxtBox.Text = rdr[0].ToString() + " | " + rdr[1].ToString();
        }
    }

 }
}
4

1 回答 1

4

您会一一获取所有记录,但以下行:

DataTxtBox.Text = rdr[0].ToString() + " | " + rdr[1].ToString();

有一个仅获取当前记录的作业。而是试试这个:

DataTxtBox.Text += rdr[0].ToString() + " | " + rdr[1].ToString();

重要的一点是+=. 这意味着行被追加而不是覆盖以前的值。

于 2013-03-03T18:31:31.893 回答