为可移植数据库应用程序创建数据库jdbc Derby

时间:2014-07-19 22:24:25

标签: java database jdbc derby

创建文件夹和derby数据库的类

package Utility_Package;

import java.io.File;

import java.io.IOException;

import java.util.logging.Level;

import java.util.logging.Logger;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.logging.Level;

import java.util.logging.Logger;




     public class systemSetup {

  String finalDirectory;

String dirName = "Car_washing_System";

Connection con = null;

Statement st = null;

public String url;

// method to create Database in the Folder
 public void createDB(){

 try {
     System.setProperty("derby.system.home",
             dirName+"/dbs");

     try {
         Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

     } catch (ClassNotFoundException ex) {

         Logger.getLogger(systemSetup.class.getName()).log(Level.SEVERE, null, ex);
     }

     con = DriverManager.getConnection(url);

     st = con.createStatement();

     st.executeUpdate("CREATE TABLE CARS(ID INT PRIMARY KEY,"
                + "NAME VARCHAR(30), PRICE INT)");
        st.executeUpdate("INSERT INTO CARS VALUES(1, 'Audi', 52642)");
        DriverManager.getConnection("jdbc:derby:;shutdown=true");

 } catch (SQLException ex) {

  Logger lgr = Logger.getLogger(systemSetup.class.getName());

        if (((ex.getErrorCode() == 50000)
                && ("XJ015".equals(ex.getSQLState())))) {

            lgr.log(Level.INFO, "Derby shut down normally", ex);

        } else {

            lgr.log(Level.SEVERE, ex.getMessage(), ex);
        }

    } finally {

        try {

            if (st != null) {

                st.close();
            }
            if (con != null) {

                con.close();
            }

        } catch (SQLException ex) {

            Logger lgr = Logger.getLogger(systemSetup.class.getName());

            lgr.log(Level.WARNING, ex.getMessage(), ex);
        }
    }
}

// Method to create the folder on the mac if does not exist 

public File createUserDirectory(){

    // Creating the directories for the java desktop application  
    final File homeDir = new File(System.getProperty("user.home"));

    final File dir = new File(homeDir, dirName);

    if (!dir.exists() && !dir.mkdirs()) {  

        finalDirectory = dir.toString();

        url = "jdbc:derby:"+finalDirectory+ "systemDb;user=USER";

        // verify if folder has been created and then check that url is not null
        if(!url.isEmpty()){
createDB();
} else {createUserDirectory();}

}return dir;
}

}

---输出 跑: 建立成功(总时间:2秒)

问题是文件编译,创建文件夹没问题,但文件夹下没有创建数据库,请任何帮助将不胜感激

0 个答案:

没有答案