简体   繁体   English

Jdbc 使用 java 连接

[英]Jdbc connection using java

I have Rest-Api in the java.我在 java 有 Rest-Api。

That will take dbUrl, dbUserName, dbPassWord, dbDriver and sql query这将采用 dbUrl、dbUserName、dbPassWord、dbDriver 和 sql 查询

and gives me the result set and after I will be converting into json format.并给我结果集,然后我将转换为 json 格式。

Class.forName("oracle.jdbc.driver.OracleDriver");
connectionUrl = "jdbc:oracle:thin:@" + server + ":" + dbName + "";
conn = DriverManager.getConnection(connectionUrl, userName, password);
try {
    stmt = conn.createStatement();
    output = resultSetHandler(stmt.executeQuery(query)); // this method convert ResultSet to Json
    } catch (SQLException e) {
        throw new Error(e);
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
} catch (SQLException e) {
    throw new Error(e);
} finally {
    try {
        if (conn != null) {
            conn.close();
        }
    } catch (SQLException ex) {
        throw new Error(ex);
    }
}

The problem here is that When 30 users use this api at one time means It will throw an error for few users.... and also I will not be using just oracle and I will be using postgres, mysql also这里的问题是,当 30 个用户同时使用这个 api 时,这意味着它会为少数用户抛出一个错误……而且我不会只使用 oracle,我还会使用 postgres,mysql

  1. Consider using DB connection pool such as Hikari or C3P0 (both available at Maven Repository).考虑使用 DB 连接池,例如HikariC3P0 (均可在 Maven Repository 获得)。 Opening a connection every time is very inefficient and you may run out of connections which may be the error you are getting.每次都打开一个连接是非常低效的,你可能会用完连接,这可能是你得到的错误。 Please post your error.请发布您的错误。
  2. Use try-with-resources instead of doing the finally block.使用 try-with-resources 而不是执行 finally 块。 It will automatically call close() on Autoclosable objects such as Connection, Statement, PreparedStatement, ResultSet, etc.它会自动调用可自动关闭对象的 close(),例如 Connection、Statement、PreparedStatement、ResultSet 等。
 try ( Connection myConnection = MyConnectionPool.getConnection(); Statement stmt = myConnection.createStatement(); ResultSet rs = stmt.executeQuery(query) ) { // Do work with rs }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM