场景:网上看到一个项目在线生成表结构,感觉这样很方便,能够节省很大的人工,也想做一个这样的项目,先尝试着写了个测试类,后续再找前端继续完善
我这边动态创建的前提是有一个存在的数据库,代码如下:
Class.forName("com.mysql.jdbc.Driver");//创建连接String url = "jdbc:mysql://172.16.10.54:3306/jeemp?useUnicode=true&characterEncoding=UTF-8" +"&verifyServerCertificate=false&useSSL=false";Connection conn = DriverManager.getConnection(url, "root", "root");Statement stat = conn.createStatement();String creatsql = "CREATE TABLE hello( "+ " id int(4) not null ,"+ " hname varchar(10) not null "+ " ) charset=utf8; ";//获取数据库表名ResultSet rs = conn.getMetaData().getTables(null, null, "hello", null);// 判断表是否存在,如果存在则什么都不做,否则创建表if(!rs.next() ){stat.executeLargeUpdate(creatsql);}
然后进行插入数据和查看数据
//添加数据stat.executeUpdate(" insert into hello values(1,'JackRen') ");stat.executeUpdate("insertinto hello values(1,'张三') ");//查询数据ResultSet result = stat.executeQuery("select * from hello");while (result.next()) {System.out.println(result.getInt("id") + "" + result.getString("hname"));}
最后别忘了要关闭数据库连接
//关闭数据库result.close();stat.close();conn.close();
我们试想下,如果我想要表名和表中的字段都是从前端传入到后台,后台拿到后进行处理,然后再写入数据库。想到这就开始做吧,我们先做理想情况下,前端拼接好的数据是一个字符串,放入到数组中,画个简图:

修改下原有代码:
/** 动态创建表字段* @author JackRen* @date 2021/2/24* @return**/private static void dynamicCreateTableFileds(String table,List<String> fileds) throws Exception{Class.forName("com.mysql.jdbc.Driver");//一开始必须必填一个已经存在的数据库String url = "jdbc:mysql://172.16.10.54:3306/jeemp?useUnicode=true&characterEncoding=UTF-8" +"&verifyServerCertificate=false&useSSL=false";Connection conn = DriverManager.getConnection(url, "root", "root");Statement stat = conn.createStatement();String sql = "CREATE TABLE "+table+"(";for (String str:fileds) {sql = sql+str;}sql = sql + " ) charset=utf8; ";//获取数据库表名ResultSet rs = conn.getMetaData().getTables(null, null, table, null);// 判断表是否存在,如果存在则什么都不做,否则创建表if(!rs.next() ){stat.executeLargeUpdate(sql);}//添加数据stat.executeUpdate(" insert into "+table+" values(1,'JackRen') ");stat.executeUpdate(" insert into "+table+" values(1,'昊天') ");//查询数据ResultSet result = stat.executeQuery("select * from "+table);while (result.next()) {System.out.println(result.getInt("id") + " " + result.getString("hname"));}//关闭数据库result.close();stat.close();conn.close();}
执行程序入口:
public static void main(String[] args) throws Exception{List<String> fileds = new ArrayList<>();fileds.add(" id int(4) not null ,");fileds.add(" hname varchar(10) not null ");dynamicCreateTableFileds("test",fileds);}
执行结果:


本文介绍了如何在SpringBoot项目中动态创建MySQL数据库表。首先,代码展示了在已有数据库下创建表的过程,接着讨论了如何接收前端传来的表结构信息,将这些信息处理后用于动态建表。通过示例代码,演示了从字符串数组中解析表结构并执行创建表的逻辑,最终展示执行结果。
4489

被折叠的 条评论
为什么被折叠?



