与MySQL在C#中工作工作、MySQL

2023-09-04 23:17:50 作者:十二骚年

下面是我的code将数据打印到终端:

Here's my code to print the data to the terminal:

public static void WriteData()
{
    string connString = "SERVER=localhost;" +
        "DATABASE=db;" +
        "UID=user;" +
        "PASSWORD=pass;";

    MySqlConnection connection = new MySqlConnection(connString);
    MySqlCommand command = connection.CreateCommand();
    MySqlDataReader reader;

    command.CommandText = "SELECT * FROM table1";
    connection.Open();
    reader = command.ExecuteReader();

    while (reader.Read())
    {
        for (int i = 0; i < reader.FieldCount; i++)
            Console.Write(reader.GetValue(i).ToString() + " ");
        Console.WriteLine();
    }
    connection.Close();
}

现在我想查看一个的DataGridView 的结果。所有我发现教程涉及添加外部数据源的网格,这是我不知道该怎么办MySQL中。 (同时请注意,我在开发Windows窗体没有经验,但我想大多数的GUI开发是拖和下降呢)。

Now I'd like to view the results in a DataGridView. All the tutorials I've found involve adding external data sources to the grid, which I have no idea how to do in MySQL. (Also please note that I have no experience in developing Windows Forms, but I guess that most GUI development is drag-and-drop anyway).

推荐答案

由于丹尼尔说,一个DataTable就足够了这一点。

As Daniel Said, a DataTable would be sufficient for this.

如果您使用DataAdapter您可以填写一个数据表,然后绑定到您的网格,如:

If you use a DataAdapter you can fill a DataTable and then bind this to your grid, e.g.:

DataGridView.DataSource = DataTable

如果您设置的DataGridView自动生成列,那么你将看到每列中的数据表,否则,您必须指定每一列。

If you set the DataGridView to auto generate columns then you will see each column in the data table, else, you need to specify each column.

下面是code从SQL命令填充数据表:

Here is the code to populate a data table from a SQL command:

using (SqlDataAdapter oSqlDataAdapter = new SqlDataAdapter(oSqlCommand))
{
    DataTable oDataTable = new DataTable();
    oSqlDataAdapter.Fill(oDataTable);
    return oDataTable;
}

显然,你应该使用SQL类的MySQL的类来代替。

Obviously you would use MySQL classes instead of SQL classes.