开发者

Working with MySQL in C#

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 < 开发者_如何学Goreader.FieldCount; i++)
            Console.Write(reader.GetValue(i).ToString() + " ");
        Console.WriteLine();
    }
    connection.Close();
}

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).


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

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

DataGridView.DataSource = DataTable

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.

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

Obviously you would use MySQL classes instead of SQL classes.


the best way to learn about this is to learn about data tables and datasets. This is pretty much the same across the board. You can do it drag and drop in visual studio but it is best to have more control over it.

this is an excellent tutorial in 4 parts

http://www.codeproject.com/KB/grid/practicalguidedatagrids1.aspx


If I'm not wrong, the mysql connector for .net has MySqlAdapter class that you can use to get a DataSet and then put the information into a Datatable or a Grid in the way WraithNath 've said.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜