C# MySql DataTable填充数组

标签 c# mysql mysqldatareader

我遇到了问题。

我想编写一个程序来将一些内容插入到 Mysql 数据库中。 第一次,我为数据库中的每一列创建一个自己的字符串,并使用它来进行 SQL 查询。但在大多数表中,我有超过 100 列。我不想创建 100 个变量。所以我决定用数据表和数组来制作它。但现在我不知道如何将列的名称填充到数组中。这是执行此操作的代码部分。

        private void button_npccreate_click(object sender, EventArgs e)
    {
        //Umwandlung von C# Variable in Mysql Variable
        MySqlCommand command = new MySqlCommand();
        command.Parameters.AddWithValue("@server", server);
        command.Parameters.AddWithValue("@port", port);
        command.Parameters.AddWithValue("@user", user);
        command.Parameters.AddWithValue("@password", mysqlpassword);
        command.Parameters.AddWithValue("@world", db_world);


        //Connection zu Mysql Server
        string myConnectionString = "Server=" + server + ";Port=" + port + ";Database=" + db_world + ";Uid=" + user + ";Pwd=" + mysqlpassword + ";";
        MySqlConnection connection = new MySqlConnection(myConnectionString);
        MySqlCommand cmd;
        cmd = connection.CreateCommand();
        string readquery = "SELECT * FROM quest_template;";
        MySqlDataAdapter read_adapter = new MySqlDataAdapter(readquery, connection);
        DataTable tableRead = new DataTable();
        connection.Open();
        read_adapter.Fill(tableRead);
        connection.Close();
        int columns = 0;


        if(tableRead.Rows.Count > 0)
        {
        foreach(DataColumn dc in tableRead.Columns)
        {
            columns++;
        }
        }
        else
        {
            MessageBox.Show("The table is empty. Please check your Database.");
        }

        string [] columns_array = new string[columns];
        foreach (DataColumn dc in tableRead.Columns)
        {
// Here i must fill the Array i think. But i dont know how to do                      this.
        }

    }

最佳答案

您应该考虑 Emmad Kareem 言论。

您的目标存在的问题是列可能包含不同类型的值。因此,您无法收集二维数组中的所有单元格(一维用于列,一维用于行)。 例如,在下面的代码中,如果要将 col0Array 和 col1array 合并到单个 2 维数组中,则需要将该数组声明为“object[,]”,这与 DataTable 相比没有优势

int   [] Col0Array = new int   [tableRead.Rows.Count] ; // first Column type is int
string[] Col1Array = new string[tableRead.Rows.Count] ; // second Column type is string
for (int i=0;tableRead.Rows.Count;i++)
{
   Col0Array[i]=(int   )tableRead.Rows[i][0] ;
   Col1Array[i]=(string)tableRead.Rows[i][1] ;
}

关于C# MySql DataTable填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31350505/

相关文章:

c# - ExecuteReader 上的 Mysql 异常

MySqlDataReader.Read() "Timeout"从一个非常大的表(超过 1 亿条记录)读取时

C# 在 UI 线程中等待

c# - C#中什么情况下不为公共(public)属性生成私有(private)变量?

java - 在 Java 中处理难看的 SQL

php - 部署一个小型 PHP + MySQL 服务

c# - Reader 不返回数据库中的所有行

c# - SavingChanges 事件与 SaveChanges 覆盖之间的区别?

C# .NET - SendKeys、SendInput、SendMessage、InputInjector 和 Cursor.Position 之间的区别

MySQL sql_mode 在 mysql 重启时重新配置