c# - mysql 整个数据库到 json 使用 c# 没有 datagridview

标签 c# mysql json

我是编程新手。以下 C# 代码使用数据 GridView 将单个表记录导出到 json 文件。该数据库包含 20 多个表,每个表都有字段 last_updatedadded_on。如何更改此代码以在不使用 datagridview 的情况下将过滤后的(使用日期时间选择器)记录从 所有表 导出到 json 文件。

private void btnFilldataGridView_Click(object sender, EventArgs e)
        {
            try
            {
                _dbConnection.Open();
                const string selectQuery =
                    "SELECT * FROM purchases WHERE (last_updated <= @dtp_last_updated) AND (added_on <= @dtp_last_updated)";

                using (var cmdLocal = new MySqlCommand(selectQuery, _dbConnection))
                {
                    cmdLocal.Parameters.Add("@dtp_last_updated", MySqlDbType.DateTime).Value =
                        DateTime.Parse(dtpLastServerUpdated.Text);
                    cmdLocal.Connection = _dbConnection;
                    cmdLocal.CommandText = selectQuery;
                    _dbDataAdapter = new MySqlDataAdapter();
                    _dbDataAdapter.SelectCommand = cmdLocal;
                    _dbDataTable = new DataTable();
                    _dbDataAdapter.Fill(_dbDataTable);
                    dataGridView1.DataSource = _dbDataTable;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            finally
            {
                _dbDataAdapter.Dispose();
                _dbConnection.Close();
            }
        }

下面的c#编码用于将datagridview View 内容转成json文件

    private void btnExportToJson_Click(object sender, EventArgs e)
    {
        var jasonData = (DataTableToJson(_dbDataTable));
        //MessageBox.Show(afd);
        System.IO.File.WriteAllText(@"C:\Users\SAKTHY-PC\Desktop\path.json", jasonData);
        Application.Exit();
    }

最佳答案

我使用以下内容

using System.Data;
using MySql.Data.MySqlClient;
using System.Web.Script.Serialization;
using System.Net;
using Newtonsoft.Json;
using System.Configuration;
using System.Net.NetworkInformation;

    private void btnExportJson_Click(object sender, EventArgs e)
    {
        string filePath = @"C:\Users\SAKTHYBAALAN-PC\Desktop\app_sample.json";

        if(File.Exists(filePath))
        {
            MessageBox.Show("Sorry! The file is already exists, Please restart the operation","File Exists");
            File.Delete(filePath);
        }
        else
        {
            MySQL mysql = new MySQL();

            var source_result = false;
            source_result = mysql.check_connection(myConString);

            if (source_result == false)
            {
                MessageBox.Show("Sorry! Unable to connect with XAMP / WAMP or MySQL.\n Please make sure that MySQL is running.", "Local Database Connection Failure"); // label1.Text = label1.Text + " ::Error In Source Connection";
            }
            else
            {
                // MessageBox.Show("Connected");
                int count = 0;

                using (var connection = new MySqlConnection(myConString))
                {
                    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(filePath))  //C:\Temp\app_erp_suneka.json"))

                    // For seperate lines may be huge capacity
                    using (var jsonWriter = new JsonTextWriter(streamWriter) { Formatting = Newtonsoft.Json.Formatting.Indented, Indentation = 2, IndentChar = ' ' })
                    //using (var jsonWriter = new JsonTextWriter(streamWriter) )
                    {
                        // one array to hold all tables
                        jsonWriter.WriteStartArray();

                        foreach (var tableName in tableNames)
                        {
                            //MessageBox.Show(tableName);
                            count += 1;

                            // 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 + " WHERE (last_updated >= '" + today + "') OR (added_on >= '" + today + "')", connection))
                            // using (var command = new MySqlCommand(@"SELECT * FROM " + tableName + " WHERE (last_updated <= '" + thisDay + "')", 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();
                        MessageBox.Show("Totally " + count + " tables circulated", "Success");
                        btnUploadToServer.Enabled = true;
                        // Application.Exit();
                        //btnUploadToServer_Click(sender, e);
                    }
                }
            }
        }
    }

关于c# - mysql 整个数据库到 json 使用 c# 没有 datagridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50934736/

相关文章:

java - JPA NamedQuery 选择特定列并返回类类型

MySQL BETWEEN 用于保存为字符串的日期

objective-c - 我如何在 JSONKit 中对 NSDate 字典进行 JSON 序列化

javascript - PHP-如何将 html 表格单元格值添加到 MYSQL 数据库

c# - 在方法中途添加泛型类型约束

c# - 将派生类添加到 DataGridView 的绑定(bind)源

c# - 我可以在一行代码中读取一个数组吗?

python - 使用 gaerdbms 方言时出现 SQLAlchemy StaleDataError

objective-c - 将参数传递给 Objective C 中的 JSON Web 服务

c# - 在数字之后的 NumericUpDown 控件中包含文本