package com.sdut.labex.KJPA;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * File: KJPA
 * Created: 2023/6/19
 * Author: springforest
 * Description:
 */

public class KJPA {
    public static void save(Object obj) throws Exception {
        StringBuffer sql = new StringBuffer("insert into");
        StringBuffer fields = new StringBuffer("(");
        StringBuffer filedValues = new StringBuffer("values(");

        Class c = obj.getClass();
        String className = c.getSimpleName().toLowerCase();
        sql.append(" " + className + " ");

        Field[] fs = c.getDeclaredFields();
        for (Field f : fs) {
            String fieldName = f.getName();
            fields.append(fieldName + ",");

            f.setAccessible(true);
            Object fieldValue = f.get(obj);
            filedValues.append("'").append(fieldValue).append("',");
        }

        fields.delete(fields.length() - 1, fields.length());
        fields.append(")");
        filedValues.delete(filedValues.length() - 1, filedValues.length());
        filedValues.append(")");

        sql.append(fields).append(filedValues);
        System.out.println(sql);

        //这行会触发Driver.class中静态初始化块的执行
        Class.forName("com.mysql.cj.jdbc.Driver");

        String url = "jdbc:mysql://106.15.196.199:3306/DCMS?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8";
        String username = "root";
        String password = "Udkklzxc123.";
        try (Connection cnn = DriverManager.getConnection(url, username, password);
             Statement stmt = cnn.createStatement()) {//Try-with-resource
            int count = stmt.executeUpdate(sql.toString());
            System.out.println(count != 0 ? "成功" : "失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
