JDBC Connectivity to Various Databases and SQL Query Syntax
This writeup gives us an idea of the jar files and the drivers required to connect to various databases. We have chosen six databases for this purpose and they are MySQL,Oracle,MS SQL Server-2000,MS SQL Server-2005,Sybase and Apache Derby.
We need to have suitable jar files to establish connections to corresponding databases. No need to set these jar files in Environment Variables or in any classpath. We will load the jar files dynamically.Here is the java code to establish connection to various DBs.
The output window appears to be like this:
What happens if a semicolon is placed at end of the query?
i.e. if queryString variable is
String queryString = "select count(*) from ads_user;";
Semicolon at the end of the Query throws an error in Oracle,Sybase and Derby DBs but works fine with MySQL and SQL Server Databases.The following errors will be in thrown,
Oracle:
Sybase:
Apache Derby:
While using a query in java code it is not recommended to use a semicolon at the end of the query.
We need to have suitable jar files to establish connections to corresponding databases. No need to set these jar files in Environment Variables or in any classpath. We will load the jar files dynamically.Here is the java code to establish connection to various DBs.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class JDBCConnectivityAndSQLQuerySyntax { private static String driver = null; private static String url = null; private static String userId = null; private static String pwd = null; String queryString = "select count(*) from ads_user;"; public static void main(String[] args) { testConnectivityAndQuerySyntax(); } public static Connection getConnection(String driver,String url, String userId,String pwd) { Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(url,userId,pwd); } catch (Exception ex) { ex.printStackTrace(); } return conn; } void loadJar(String jarFilePath) throws IOException { try { URLClassLoader cl = (URLClassLoader) getClass().getClassLoader(); URL url = new URL("file", null,jarFilePath); Class c = URLClassLoader.class; Method method = c.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(cl, url); } catch (Exception ex) { ex.printStackTrace(); } } public static void closeResources(Statement stm, ResultSet rs, Connection conn) { try { if(rs != null){ rs.close(); } if(stm != null){ stm.close(); } if (conn != null) { conn.close(); } } catch(Exception ex){ rs = null; stm = null; conn = null; } } public void connectToMySQL() { Connection conn = null; Statement stm = null; ResultSet rs = null; try { driver = "com.mysql.jdbc.Driver"; url = "jdbc:mysql://localhost:3306/mysql_db"; userId = "mysql_db"; pwd = "mysql_db"; loadJar("C:/jdbc_jars/mysql/mysql-connector-java-5.0.3-bin.jar"); conn = getConnection(driver, url, userId, pwd); stm = conn.createStatement(); rs = stm.executeQuery(queryString); while(rs.next()) { System.out.println(getDBNameAndVersion(conn)+" ### Total count: "+rs.getString(1)); } } catch (Exception ex) { ex.printStackTrace(); } finally { closeResources(stm, rs, conn); } } public void connectToOracle() { Connection conn = null; Statement stm = null; ResultSet rs = null; try { driver = "oracle.jdbc.driver.OracleDriver"; url = "jdbc:oracle:thin:@192.168.2.90:1521:orcldb"; userId = "orcl_r1"; pwd = "orcl_r1"; loadJar("C:/jdbc_jars/oracle/ojdbc14.jar"); conn = getConnection(driver, url, userId, pwd); stm = conn.createStatement(); rs = stm.executeQuery(queryString); while(rs.next()) { System.out.println(getDBNameAndVersion(conn)+" ### Total count: "+rs.getString(1)); } } catch (Exception ex) { ex.printStackTrace(); } finally { closeResources(stm, rs, conn); } } public void connectToSybase() { Connection conn = null; Statement stm = null; ResultSet rs = null; try { driver = "com.sybase.jdbc2.jdbc.SybDriver"; url = "jdbc:sybase:Tds:192.168.2.91:5000/sybase_db"; userId = "sybaseuser"; pwd = "sybaseuser"; loadJar("C:/jdbc_jars/sybase/jconn2.jar"); conn = getConnection(driver, url, userId, pwd); stm = conn.createStatement(); rs = stm.executeQuery(queryString); while(rs.next()) { System.out.println(getDBNameAndVersion(conn)+" ### Total count: "+rs.getString(1)); } } catch (Exception ex) { ex.printStackTrace(); } finally { closeResources(stm, rs, conn); } } public void connectToSqlServer2000() { Connection conn = null; Statement stm = null; ResultSet rs = null; try { driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; url = "jdbc:sqlserver://192.168.2.92:1433;databasename=sqlserverdb_2000;selectMethod=cursor"; userId = "sqlserverdb"; pwd = "sqlserverdb"; loadJar("C:/jdbc_jars/mssql2000/msbase.jar"); loadJar("C:/jdbc_jars/mssql2000/mssqlserver.jar"); loadJar("C:/jdbc_jars/mssql2000/msutil.jar"); conn = getConnection(driver, url, userId, pwd); stm = conn.createStatement(); rs = stm.executeQuery(queryString); while(rs.next()) { System.out.println(getDBNameAndVersion(conn)+" ### Total count: "+rs.getString(1)); } } catch (Exception ex) { ex.printStackTrace(); } finally { closeResources(stm, rs, conn); } } public void connectToSqlServer2005() { Connection conn = null; Statement stm = null; ResultSet rs = null; try { driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; url = "jdbc:sqlserver://192.168.2.93:1433;databasename=sqlserverdb_2005;"; userId = "sa"; pwd = "sa1"; loadJar("C:/jdbc_jars/sqlserver2005/sqljdbc.jar"); conn = getConnection(driver, url, userId, pwd); stm = conn.createStatement(); rs = stm.executeQuery(queryString); while(rs.next()) { System.out.println(getDBNameAndVersion(conn)+" ### Total count: "+rs.getString(1)); } } catch (Exception ex) { ex.printStackTrace(); } finally { closeResources(stm, rs, conn); } } public void connectToDerby() { Connection conn = null; Statement stm = null; ResultSet rs = null; try { driver = "org.apache.derby.jdbc.EmbeddedDriver"; url = "jdbc:derby:/DerbyDB/SampleDerbyDB"; userId = "derbyuser"; pwd = "derbyuser"; loadJar("C:/jdbc_jars/derby/derby.jar"); conn = getConnection(driver, url, userId, pwd); stm = conn.createStatement(); rs = stm.executeQuery(queryString); while(rs.next()) { System.out.println(getDBNameAndVersion(conn)+" ### Total count: "+rs.getString(1)); } } catch (Exception ex) { ex.printStackTrace(); } finally { closeResources(stm, rs, conn); } } public String getDBNameAndVersion(Connection conn) { String str = null; try { DatabaseMetaData metaData = conn.getMetaData(); str = (metaData.getDatabaseProductName()+" "+metaData.getDatabaseProductVersion()); } catch (Exception ex) { ex.printStackTrace(); } return str; } public static void testConnectivityAndQuerySyntax(){ BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("\nPlease select the type of database you want to use\n"); System.out.println(" -> 1- MySQL"); System.out.println(" 2- Oracle"); System.out.println(" 3- Sybase"); System.out.println(" 4- SQLServer-2000"); System.out.println(" 5- SQLServer-2005"); System.out.println(" 6- Apache Derby"); System.out.println(" 7- Select All"); System.out.println("\nEnter the number of your choice or pressto accept the default:"); try { String inputString = bufferedReader.readLine(); int input = 1; if(inputString != null && !inputString.equals("")) { input = Integer.parseInt(inputString); } JDBCConnectivityAndSQLQuerySyntax connectivityAndSyntax = new JDBCConnectivityAndSQLQuerySyntax(); switch(input){ case 1: connectivityAndSyntax.connectToMySQL(); break; case 2: connectivityAndSyntax.connectToOracle(); break; case 3: connectivityAndSyntax.connectToSybase(); break; case 4: connectivityAndSyntax.connectToSqlServer2000(); break; case 5: connectivityAndSyntax.connectToSqlServer2005(); break; case 6: connectivityAndSyntax.connectToDerby(); break; case 7: connectivityAndSyntax.connectToMySQL(); connectivityAndSyntax.connectToOracle(); connectivityAndSyntax.connectToSybase(); connectivityAndSyntax.connectToSqlServer2000(); connectivityAndSyntax.connectToSqlServer2005(); connectivityAndSyntax.connectToDerby(); break; default: System.out.println("Invalid Input"); } System.out.println("\nRepeat the process again <y/n>: "); BufferedReader _bufferedReader = new BufferedReader(new InputStreamReader(System.in)); String readLine = _bufferedReader.readLine(); if("Y".equalsIgnoreCase(readLine)){ testConnectivityAndQuerySyntax(); } else { if(!readLine.equalsIgnoreCase("N")) { System.out.println("Invalid Input."); } } } catch (Exception ex) { System.out.println("Invalid Input."); } } }
The output window appears to be like this:
What happens if a semicolon is placed at end of the query?
i.e. if queryString variable is
String queryString = "select count(*) from ads_user;";
Semicolon at the end of the Query throws an error in Oracle,Sybase and Derby DBs but works fine with MySQL and SQL Server Databases.The following errors will be in thrown,
Oracle:
java.sql.SQLException: ORA-00911: invalid character at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134) at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289) at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:590) at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1973) at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:850) at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2599) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2963) at oracle.jdbc.driver.OracleStatement.executeQuery(OracleStatement.java:653)
Sybase:
com.sybase.jdbc2.jdbc.SybSQLException: Incorrect syntax near ';'. at com.sybase.jdbc2.tds.Tds.processEed(Tds.java:2636) at com.sybase.jdbc2.tds.Tds.nextResult(Tds.java:1996) at com.sybase.jdbc2.jdbc.ResultGetter.nextResult(ResultGetter.java:69) at com.sybase.jdbc2.jdbc.SybStatement.nextResult(SybStatement.java:204) at com.sybase.jdbc2.jdbc.SybStatement.nextResult(SybStatement.java:187) at com.sybase.jdbc2.jdbc.SybStatement.queryLoop(SybStatement.java:1510) at com.sybase.jdbc2.jdbc.SybStatement.executeQuery(SybStatement.java:1495) at com.sybase.jdbc2.jdbc.SybStatement.executeQuery(SybStatement.java:402)
Apache Derby:
java.sql.SQLException: Syntax error: Encountered ";" at line 1, column 30. at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source) at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source) at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source) at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source) at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source) at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source) at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source) at org.apache.derby.impl.jdbc.EmbedStatement.executeQuery(Unknown Source)Base Line
While using a query in java code it is not recommended to use a semicolon at the end of the query.
Nice article. Great. I will try this out....
ReplyDelete