You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从MySQL取数到C# WinForms并将10行数据存入对应字符串

最优实现方案:读取10行type值并存储

Hey there! Let's work through this step by step. First, I want to point out that using individual variables like string1 to string10 isn't the most flexible approach—collections like List<string> are far easier to maintain, especially if your row count changes later. But I'll cover both the recommended flexible method and the direct variable assignment if you specifically need that.

This method is cleaner, more scalable, and avoids messy individual variable management. Here's how to do it:

// Initialize a list to store all type values
List<string> typeValues = new List<string>();
// Only select the 'type' column (more efficient than SELECT *) and sort by ID to ensure order matches your string1-string10 expectation
string query = "SELECT type FROM data ORDER BY ID";

// Use 'using' statements to automatically dispose resources (prevents memory leaks, even if an error occurs)
using (MySqlConnection connect = new MySqlConnection(info))
using (MySqlCommand dbcommand = new MySqlCommand(query, connect))
{
    try
    {
        connect.Open();
        // Wrap the reader in 'using' too to handle cleanup
        using (MySqlDataReader myreader = dbcommand.ExecuteReader())
        {
            while (myreader.Read())
            {
                // Handle possible NULL values in the 'type' column to avoid conversion errors
                string type = myreader["type"] is DBNull ? string.Empty : myreader["type"].ToString();
                typeValues.Add(type);
            }
        }
    }
    catch (Exception ex)
    {
        // Always add meaningful error handling (e.g., log the error or notify the user)
        MessageBox.Show($"Failed to read data: {ex.Message}");
    }
}

// If you still need to map to string1-string10
if (typeValues.Count >= 10)
{
    string string1 = typeValues[0];
    string string2 = typeValues[1];
    string string3 = typeValues[2];
    string string4 = typeValues[3];
    string string5 = typeValues[4];
    string string6 = typeValues[5];
    string string7 = typeValues[6];
    string string8 = typeValues[7];
    string string9 = typeValues[8];
    string string10 = typeValues[9];
}
else
{
    MessageBox.Show("The database has fewer than 10 rows of data.");
}

Why This Is Better:

  • Automatic Resource Management: The using statements ensure your database connection, command, and reader are properly disposed of, even if an exception is thrown. No need to manually call Close() anymore!
  • Efficiency: Querying only the type column instead of SELECT * reduces data transfer between your app and the database.
  • Order Guarantee: Adding ORDER BY ID ensures the rows are returned in the same order as your string1 to string10 mapping (so string1 matches ID=1, etc.).
  • NULL Safety: We check for DBNull to avoid crashes if the type column has empty values.
  • Scalability: If your row count changes later, you don't need to rewrite variable declarations—just adjust how you use the list.

Alternative: Direct Variable Assignment (If You Must)

If you specifically need to assign values directly to string1 to string10, here's a way to do it cleanly (though less scalable):

// Initialize all variables with default empty strings
string string1 = string.Empty;
string string2 = string.Empty;
string string3 = string.Empty;
string string4 = string.Empty;
string string5 = string.Empty;
string string6 = string.Empty;
string string7 = string.Empty;
string string8 = string.Empty;
string string9 = string.Empty;
string string10 = string.Empty;

string query = "SELECT type FROM data ORDER BY ID";
int currentRow = 0;

using (MySqlConnection connect = new MySqlConnection(info))
using (MySqlCommand dbcommand = new MySqlCommand(query, connect))
{
    try
    {
        connect.Open();
        using (MySqlDataReader myreader = dbcommand.ExecuteReader())
        {
            // Stop once we've read 10 rows or run out of data
            while (myreader.Read() && currentRow < 10)
            {
                string type = myreader["type"] is DBNull ? string.Empty : myreader["type"].ToString();
                // Assign to the correct variable based on row index
                switch (currentRow)
                {
                    case 0: string1 = type; break;
                    case 1: string2 = type; break;
                    case 2: string3 = type; break;
                    case 3: string4 = type; break;
                    case 4: string5 = type; break;
                    case 5: string6 = type; break;
                    case 6: string7 = type; break;
                    case 7: string8 = type; break;
                    case 8: string9 = type; break;
                    case 9: string10 = type; break;
                }
                currentRow++;
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"Failed to read data: {ex.Message}");
    }
}

// Check if all 10 variables were populated
if (currentRow < 10)
{
    MessageBox.Show("Not enough rows found in the database.");
}

Note:

This method works but becomes cumbersome if you ever need to handle more or fewer than 10 rows. The List<string> approach is almost always the better choice for maintainability.

内容的提问来源于stack exchange,提问作者Mr. Zex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:02:43