Changing databases in jdbc sql server connection

How to change the default database to which access connects? For example, im trying to get a list of each table on sql server connected to:

List list = new ArrayList();
for (String db: dbList) {
    conn.prepareStatement("use ["+db+"]").executeQuery();//THIS LINE ISNT WORKING D:
    DatabaseMetaData md = conn.getMetaData();
    rs = md.getTables(null, null, "%", null);
    while (rs.next())
        list.add(rs.getString(3));
}
return list;

A line that does not work causes this error:

com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:171)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:394)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:340)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4575)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1400)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:179)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:154)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:283)

Creating a new connection for each db is not an option.

+4
source share
1 answer

You cannot use executeQuery()for this, you need to use execute()(and the error message gives you good advice). Use PreparedStatementalso does not make sense here.

Statement, :

Statement stmt = conn.createStatement();
stmt.execute("use [" + db + "]");
stmt.close();

() Connection.setCatalog() , 100%, Microsoft

+3

Source: https://habr.com/ru/post/1610593/


All Articles