java 调用mysql 创建表_JAVA 执行MYSQL脚本(创建数据库,建表等)

();

try {

InputStream sqlFileIn = MySqlSuperDao.class

.getResourceAsStream("/MySql/createDB.sql");

// 将SQL脚本产生为listStringBuffer sqlSb = new StringBuffer();

byte[] buff = new byte[1024];

int byteRead = 0;

while ((byteRead = sqlFileIn.read(buff)) != -1) {

sqlSb.append(new String(buff, 0, byteRead, "utf-8"));

}

String[] sqlArr = sqlSb.toString().split(

"(;\\s*\\r\\n)|(;\\s*\\n)");

// 替换数据库名

int replace = 0;

for (int i = 0; i < sqlArr.length; i++) {

if (replace == 2) {

break;

}

if (sqlArr[i].indexOf("@@@dbName@@@") > -1) {

sqlArr[i] = sqlArr[i].replace("@@@dbName@@@", dbName);

replace++;

}

}

// 将数组转成LIST并且过滤LOCKTABLE 和注释

for (int i = 0; i < sqlArr.length; i++) {

String sql = sqlArr[i].replaceAll("--.*", "").trim();

if (!sql.equals("") && sql.indexOf("LOCK TABLES") != 0

&& sql.indexOf("UNLOCK TABLES") != 0

&& sql.indexOf("/*") != 0) {

sqlList.add(sql);

}

}

} catch (Exception e) {

System.out.println("error");

return false;

}

// 创建数据库链接并执行SQL脚本

conn = this.getConnection();

stmt = null;

conn.setAutoCommit(false);

stmt = conn.createStatement();

for (String sql : sqlList) {

stmt.addBatch(sql);

}

stmt.executeBatch();

success = true;

} catch (Exception e) {

// 如果报错,则删除D

conn = null;

conn = this.getConnection();

stmt = null;

conn.setAutoCommit(false);

stmt = conn.createStatement();

stmt.execute("drop database " + dbName);

success = false;

} finally {

if (stmt != null) {

stmt.close();

}

if (conn != null) {

conn.close();

}

return success;

}

}

/**

* 获取数据库链接

*

* @author HeCheng

* @time 2011-02-26 10:48:24

* @return

* @throws SQLException

* @throws IOException

* @throws ClassNotFoundException

*/

private Connection getConnection() throws SQLException, IOException,

ClassNotFoundException {

Connection con = null;

Class.forName("com.mysql.jdbc.Driver");

Properties properties = new Properties();

properties.load(MySqlSuperDao.class

.getResourceAsStream("/MySql/DB.properties"));

String url = properties.getProperty("url");

String u = properties.getProperty("u");

String p = properties.getProperty("p");

con = DriverManager.getConnection("jdbc:mysql://" + url + "", u, p);

return con;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值