通过检查来决定是否建表
如果表尚未被建立,就执行ptmt语句更新,在数据库中创建这个表,
如果这个表已经存在,就不执行建表操作了;
package SQLCon; import java.sql.*; public class CreateTables { public static boolean HaveTable(String TableName) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); String user = "root"; String pwd = "123456"; String url = "jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false"; Connection conn = DriverManager.getConnection(url, user, pwd); ResultSet rs = conn.getMetaData().getTables(null, null, TableName, null); if(rs.next()) { rs.close(); conn.close(); return true; }else { rs.close(); conn.close(); return false; } } public static void main(String args[]) throws SQLException, ClassNotFoundException { Class.forName("com.mysql.jdbc.Driver"); String user = "root"; String pwd = "123456"; String url = "jdbc:mysql://localhost:3306/activiti?useUnicode=true&characterEncoding=utf-8&useSSL=false"; Connection conn = DriverManager.getConnection(url, user, pwd); if(HaveTable("MyTables")!=true){ String sql = "CREATE TABLE ACT_SHIP_USER "+ "(ID_ VARCHAR(64) not NULL, " + "ORG_ VARCHAR(255), " + "JOB_ VARCHAR(255), "+ "PRIMARY KEY (ID_))"; PreparedStatement ptmt = conn.prepareStatement(sql); ptmt.executeUpdate(sql); ptmt.close(); } else { System.out.println("table is existed!"); } } }
原文地址:https://www.cnblogs.com/masterchd/p/9158936.html
时间: 2024-10-08 09:24:04