Connect MySql using java to convert all data to Json

Keywords: MySQL Java JSON Database

Connect MySql using java to convert all data to Json (without using the Spring Framework)

This is the first exercise to do in the company, it is relatively simple.
Two jar s were used:
gson-2.8.0.jar and mysql-connector-java-5.1.30-bin.jar

The first thought is to connect to the database:

public class ConnectSQL {
    // URL points to the database name to be accessed
    public static final String url = "jdbc:mysql://192.168.1.1:3306/databasename?zeroDateTimeBehavior=convertToNull";
    // Driver Name
    public static final String name = "com.mysql.jdbc.Driver";
    // User name when MySQL is configured
    public static final String user = "username";
    // Password for MySQL configuration
    public static final String password = "password";

    public Connection conn = null;
    public PreparedStatement pst = null;

    public ConnectSQL(String sql) {
        try {
            Class.forName(name);// Specify Connection Type
            conn = DriverManager.getConnection(url, user, password);// Get Connections
            pst = conn.prepareStatement(sql);// Prepare to execute statement
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            this.conn.close();
            this.pst.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Url ends up with zeroDateTimeBehavior=convertToNull when connecting to the database because the database test had a field Date:0000-00-00:00:00:00
Output java error prompt:
Value 0000-00-00 00:00:00 can not be represented as java.sql.Timestamp.
This is because MySQL uses this date to represent an invalid date and has found two solutions:
1. Use zeroDateTimeBehavior=convertToNull and output Date:null as final result
2. Use zeroDateTimeBehavior=round and output Date:0001-01-01 00:00:00
The solution is by reference https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html Given the property of zeroDateTimeBehavior, I use the first direct conversion to null here

After connecting, because you need to get data for all tables in the database, you get all the tablenames first
DatabaseMetaData meta = (DatabaseMetaData) con.getMetaData();
ResultSet rs = meta.getTables(null, null, null, new String[] { "TABLE" });
while (rs.next()) {
arrTablenames.add(rs.getString(3));
}
Then, execute the sql statement for each table:

static ArrayList<String> arrcolname = new ArrayList<String>();
static ArrayList<String> arrcolout = new ArrayList<String>();
public static ResultSet execSQL(String strtablename) {
    String strsql = null;
    ConnectSQL db1 = null;
    ResultSet ret = null;
    strsql = "select * from " + strtablename;// SQL statement
    db1 = new ConnectSQL(strsql);// Create ConnectSQL Object
    try {
        ret = db1.pst.executeQuery();// Execute statement to get result set
        while (ret.next()) {
            ResultSetMetaData rsmd = ret.getMetaData();
            int icolnum = rsmd.getColumnCount();
            for (int i = 1; i <= icolnum; i++) {
                arrcolname.add(rsmd.getColumnName(i).toString());//table field name
                arrcolout.add(ret.getString(i));//table content
            }
        }
        ret.close();
        db1.close();// Close Connection
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return ret;
}

The field names and contents of each table are saved in ArrayList <String> and can be edited by yourself, such as adding a key to become a Map.

Finally, use Gson to convert the resulting Java type (such as Map) to Json format

public static String ToJson(LinkedHashMap<String, Object> mTotalOut) {
    String strJsonOut = new String();
    // toJson
    GsonBuilder gsonbuilder = new GsonBuilder().setPrettyPrinting().serializeNulls();
    Gson gson = gsonbuilder.create();
    strJsonOut = gson.toJson(mTotalOut);
    return strJsonOut;
}

You started with gson.toJson(mTotalOut) directly, didn't use GsonBuilder, and found that the output was wrong.
Because a field in the table is null, gson defaults to ignore null values
For example, there are two fields UseName and Age in tblUser, the Age of User1 is null, and the output to Json is {} instead of {User1:null}, as expected.
So I added it

GsonBuilder gsonbuilder = new GsonBuilder().serializeNulls(); 
Gson gson = gsonbuilder.create();

Solve the problem of not outputting Gson null values.
Solution Reference https://github.com/google/gson/blob/master/UserGuide.md#TOC-Null-Object-Support

setPrettyPrinting()

If not used, the end result is printed on a single line of String, and setPrettyPrinting() formats the Json that is last printed on the console or output, making the output more beautiful without affecting the result of Json.

Posted by artiemus on Mon, 24 Jun 2019 10:21:46 -0700