jdbc mysql動態建表
阿新 • • 發佈:2018-06-09
通過 found exc arch 是否 cal ESS name mar
通過檢查來決定是否建表
如果表尚未被建立,就執行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!"); } } }
jdbc mysql動態建表