Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.bowprog.sql.constructeur; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.logging.Level; import java.util.logging.Logger; import org.json.simple.JSONObject; /** * construit la table * * @author micmonay */ public class Table { private final Statement statement; private String tableName; private ArrayList<String> fkSQL = new ArrayList<String>(); public Table(Statement statement) { this.statement = statement; } public boolean appliqueJSON(JSONObject jSONObject) { fkSQL.clear(); Collection<String> str = jSONObject.keySet(); for (String table : str) { try { JSONObject tableColonne = (JSONObject) jSONObject.get(table); tableName = table; String col = createCol(tableColonne); String sql = "CREATE TABLE IF NOT EXISTS `" + tableName + "`(" + col + ")"; statement.execute(sql); } catch (SQLException ex) { Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex); return false; } } for (String sql : fkSQL) { try { statement.execute(sql); } catch (SQLException ex) { Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex); return false; } } return false; } public String createCol(JSONObject tableColonne) { String strQuery = "`id` INT NOT NULL AUTO_INCREMENT"; Collection<String> str = tableColonne.keySet(); for (String colName : str) { strQuery += ",`" + colName + "` "; JSONObject colonne = (JSONObject) tableColonne.get(colName); String type = (String) colonne.get("type"); strQuery += type; if (colonne.containsKey("size")) { Long size = (Long) colonne.get("size"); strQuery += "(" + size + ")"; } if (colonne.containsKey("fk_table")) { String tableFK = (String) colonne.get("fk_table"); //fkSQL.add(" ALTER TABLE " + tableName + " ADD CONSTRAINT fk_" + tableFK + " FOREIGN KEY(" + colName + ") REFERENCES " + tableFK + "(id)"); } } strQuery += ",PRIMARY KEY (id)"; return strQuery; } public void getTableName() { } }