如何使用C#将数据库中的所有表所有记录导出到json中

时间:2018-06-18 10:33:31

标签: c# mysql json

我正在为超市创建一个ERP工具。业主在两个不同的地方有两家超市。因此,要管理超市,应将本地数据库(mySQL)同步到Web服务器。 目前,我使用以下C#代码通过使用列sales_productsadded_on过滤记录,从我的数据库中导出表(last_updated)的所有记录。我的数据库包含20多个表和更多记录。

private void button1_Click(object sender, EventArgs e)
{
        string json = string.Empty;
        List<object> objects = new List<object>();
        MySqlConnection _dbConnection = new MySqlConnection("Server = localhost; Database = app_erp_suneka; Uid = root; Pwd = ;");
        {
           _dbConnection.Open();// .Open();
           using (MySqlCommand command = _dbConnection.CreateCommand())
            {
                command.CommandText = "SELECT * FROM sales_products";
                using (MySqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        IDictionary<string, object> record = new Dictionary<string, object>();
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            record.Add(reader.GetName(i), reader[i]);
                        }
                        objects.Add(record);
                    }
                }
            }
        }
        json = JsonConvert.SerializeObject(objects);
        using (StreamWriter sw = new StreamWriter(File.Create(@"C:\Users\SAKTHY-PC\Desktop\path.json")))// "C:\\path\\file.json")))
        {
            sw.Write(json);
        }
}

我的问题是:

如何使用C#从all tables将所有记录导出到json文件?

2 个答案:

答案 0 :(得分:1)

JSON仅具有有限数量的数据类型(字符串,浮点数,布尔值,null);通过将MySQL数据导出为JSON,可能会失去精度(因为DATETIMETIMESTAMPGUIDBLOB等必须转换为字符串)。

但是,如果您仍然想将数据库导出为JSON,首先需要找到数据库中的所有表(通过查询information_schema.tables表),然后遍历每个表,选择所有行并转储它们转换为JSON。因为这可能是大量数据,所以要避免用完内存,您需要将结果流式传输到输出文件(而不是在内存中创建大量对象,然后将它们转换为JSON)。这需要使用低级JSON编写API,因此您需要确保WriteStartObjectWriteEndObject调用正确配对以创建有效的JSON。

以下程序片段演示了此技术:

using (var connection = new MySqlConnection("Server = localhost; Database = app_erp_suneka; Uid = root; Pwd = ;"))
{
    connection.Open();

    // get the names of all tables in the chosen database
    var tableNames = new List<string>();
    using (var command = new MySqlCommand(@"SELECT table_name FROM information_schema.tables where table_schema = @database", connection))
    {
        command.Parameters.AddWithValue("@database", "app_erp_suneka");
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
                tableNames.Add(reader.GetString(0));
        }
    }

    // open a JSON file for output; use the streaming JsonTextWriter interface to avoid high memory usage
    using (var streamWriter = new StreamWriter(@"C:\Temp\app_erp_suneka.json"))
    using (var jsonWriter = new JsonTextWriter(streamWriter) { Formatting = Newtonsoft.Json.Formatting.Indented, Indentation = 2, IndentChar = ' ' })
    {
        // one array to hold all tables
        jsonWriter.WriteStartArray();

        foreach (var tableName in tableNames)
        {
            // an object for each table
            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("tableName");
            jsonWriter.WriteValue(tableName);
            jsonWriter.WritePropertyName("rows");

            // an array for all the rows in the table
            jsonWriter.WriteStartArray();

            // select all the data from each table
            using (var command = new MySqlCommand($@"SELECT * FROM `{tableName}`", connection))
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    // write each row as a JSON object
                    jsonWriter.WriteStartObject();
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        jsonWriter.WritePropertyName(reader.GetName(i));
                        jsonWriter.WriteValue(reader.GetValue(i));
                    }
                    jsonWriter.WriteEndObject();
                }
            }

            jsonWriter.WriteEndArray();
            jsonWriter.WriteEndObject();
        }

        jsonWriter.WriteEndArray();
    }
}

答案 1 :(得分:0)

@Bradley Grainger,很高兴听到。但是我不能保证,我的本地dB始终有最少的记录可以使用JsonSerializer。在功能时间内(例如新年或圣诞节...),会有更多的交易,因此dB会越来越大。

相关问题