Java Database Derby Instance 1(四)

2014-11-24 07:11:53 · 作者: · 浏览: 2
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}

/**
* create and connect a database
* @param databaseName
* @param user
* @param password
* @return a connection to the URL
* @throws SQLException
*/
public static Connection createDatabaseAndGetConnection(String databaseName, String user, String password) throws SQLException{
//create and connect the database
Properties props=new Properties();
props.put("user",user);
props.put("password",password);
if(port==null){
if(ip!=null){
System.out.println("You seem to have set an ip address, if so, you have also to assign a port before loading the driver, or else an embedded database is automatically used");
}
con=DriverManager.getConnection("jdbc:derby:"+databaseName+";create=true", props);
System.out.println("Connection is successfully established, it uses an Embedded database");
}else if(ip==null){
con=DriverManager.getConnection("jdbc:derby://localhost:"+port+"/"+databaseName+";create=true", props);
System.out.println("Connection is sucessfully established, it uses an network database but stored in the local host via the port: "+port);
}else{
con=DriverManager.getConnection("jdbc:derby://"+ip+":"+port+"/"+databaseName+";create=true", props);
System.out.println("Connection is sucessfully established, it uses an network database whose host ip is: "+ip+" and via the port: "+port);
}
return con;
}

/**
* Shut down a specified database. But it doesn't matter that later we could also connect to another database.
* Because the Derby engine is not closed.
* @param databaseName
*/
public static void shutdownDatabase(String databaseName){
boolean gotSQLExc = false;
if(port==null){
try {
DriverManager.getConnection("jdbc:derby:"+databaseName+";shutdown=true");
} catch (SQLException se) {
if ( se.getSQLState().equals("08006") ) {
gotSQLExc = true;
}
}
if (!gotSQLExc) {
System.out.println("Database did not shut down normally");
} else {
System.out.println("Database: "+databaseName+" shut down normally");
}
}else if(ip==null){
try {
DriverManager.getConnection("jdbc:derby://localhost:"+port+"/"+databaseName+";shutdown=true");
} catch (SQLException se) {
// TODO Auto-generated catch block
if ( se.getSQLState().equals("08006") ) {
gotSQLExc = true;
}
}
if (!gotSQLExc) {
System.out.println("Database did not shut down normally");
} else {
System.out.println("Database: "+databaseName+" shut down normally");
}
}else{
try {
DriverManager.getConnection("jdbc:derby:/