无法使用jdbc java连接到hsqldb

时间:2019-07-24 15:41:46

标签: java database jdbc database-connection hsqldb

我在Java应用程序中使用jdbc连接到hsqldb时遇到问题。从json解析主类到Java后,我在列表中得到3个对象,这些对象正试图保存到数据库中。

这是道课

public class EventDao {
private static final String URL = "jdbc:hsql:file:C:/Applications/appName//APPFOLDER";
private static final String USER = "sa";
private static final String PASS = "";
private Connection connection;

public EventDao() {
    try {
        Class.forName("org.hsqldb.jdbcDrive");
        connection = DriverManager.getConnection(URL, USER, PASS);
    } catch (ClassNotFoundException e) {
        System.out.println("Couldnot establish connection");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

public void save(Event event) {
    final String sql = "insert into event(id,state,timestamp,type,host,alert) values (?,?,?,?,?,?)";
    try {
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, event.getId());
        preparedStatement.setString(2, event.getState());
        preparedStatement.setString(3, event.getTimestamp().toString());
        preparedStatement.setString(4, event.getType());
        preparedStatement.setString(5, event.getHost());
        preparedStatement.setString(6, event.getAlert().toString());
        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

public void close() {
    try {
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

当我尝试将对象事件保存到db(列表中有3个对象)时,这是主要的

public static void main(String[] args) {
    EventParser eventParser = new EventParser();
    eventParser.mainLoop();
}

public void mainLoop() {
    try {
        EventDao eventDao = new EventDao();
        Map<String, EventWrapper> eventsFromFile = readEventsFromFile();
        List<Event> eventsToSave = calculateEventTime(eventsFromFile);
        for (Event event : eventsToSave) {
            eventDao.save(event);
        }
        eventDao.close();
        System.out.println(eventsFromFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

调试后,我发现该连接为空。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

URL的正确格式为:

URL = "jdbc:hsqldb:file:C:/Applications/appName/APPFOLDER";

Class.forName("org.hsqldb.jdbcDrive")确保HSQLDB jar位于您的类路径中,并从jar中加载JDBC驱动程序类。这样做没有错误。错误消息表明没有驱动程序可用于错误的jdbc:hsql:file网址。