java 动态创建数据库和动态连接数据库
项目中有一个需求要动态创建数据库并且要动态连接数据库,本来以为还很难实现呢,在网上找了好久,都不是很理想,最后看到有人说创建数据库时,先连接到任意一个数据库,获得连接后用createStatement()语句创建自己的数据库,自己试了一下,果然可以.动态连接数据库就跟简单了!下面是代码,仅供参考!这些在jdbc里面实现的,如果是用hibernate的话,不知道怎么样,我没有试过!
package com.cn.javaEE.dataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateDataSource {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String database = "test2";
new CreateDataSource().getConn(database);
}
String mysqlDriver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test1";
String newUrl = "jdbc:mysql://localhost:3306/";
String username = "root";
String password = "root";
Connection conn = null;
Connection newConn = null;
public Connection getConn(String database) {
try {
Class.forName(mysqlDriver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String tableSql = "create table t_user (username varchar(50) not null primary key,"
+ "password varchar(20) not null ); ";
String databaseSql = "create database " + database;
conn = DriverManager.getConnection(url, username, password);
Statement smt = conn.createStatement();
if (conn != null) {
System.out.println("数据库连接成功!");
smt.executeUpdate(databaseSql);
newConn = DriverManager.getConnection(newUrl + database,
username, password);
if (newConn != null) {
System.out.println("已经连接到新创建的数据库:" + database);
Statement newSmt = newConn.createStatement();
int i = newSmt.executeUpdate(tableSql);//DDL语句返回值为0;
if (i == 0) {
System.out.println(tableSql + "表已经创建成功!");
}
}
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return conn;
}
}
转自http://hi.baidu.com/200770842223/blog/item/971cb3fbdae91a6d034f5645.html