Exception in thread "main" java.lang.StackOverflowError when calling function getConnection() - java

I am getting the error when compiling my project-
Exception in thread "main" java.lang.StackOverflowError
at sun.reflect.Reflection.getCallerClass(Native Method)
at java.lang.ClassLoader.getCallerClassLoader(Unknown Source)
at java.lang.Class.forName(Unknown Source)
at testpackage.DriverManager.getConnection(DriverManager.java:14)
at testpackage.DriverManager.getConnection(DriverManager.java:20)
at testpackage.DriverManager.getConnection(DriverManager.java:20)
Here is my first file code-
package testpackage;
import java.sql.*;
import javax.swing.JOptionPane;
class DriverManager {
static Connection dbConnection = null;
public static Connection getConnection(String String_url, String USER, String PASS) throws SQLException
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//JOptionPane.showMessageDialog(null, "driver load successfully");
} catch (ClassNotFoundException e) {
e.printStackTrace();
//JOptionPane.showMessageDialog(null, "driver load failed");
}
dbConnection = DriverManager.getConnection(String_url,USER,PASS);
return dbConnection;
}
}
I called this method in another file-
package testpackage;
import java.awt.Rectangle;
import org.openqa.selenium.firefox.FirefoxDriver;
public class testclass {
public static void main (String[] args) throws Exception
{
DriverManager Connection_getConnection = new DriverManager();
Connection_getConnection.getConnection("database string url","username","password");
}
}
Note- I have used alert to debug the issue and find function calls recursively because i am getting alert one after one.

Your DriverManager.getConnection() method consists in calling DriverManager.getConnection(), which consists in calling DriverManager.getConnnection(), ...
That's because you chose to name your class and method the same way as the standard java.sql.DriverManager.getConnection().

It looks like you're calling:
dbConnection = DriverManager.getConnection(String_url,USER,PASS);
before ever returning a value, and since that is the method you're currently in you are recursively calling this method causing an infinite loop.
The getConnection(...) method is calling the getConnection(...) method which will never end and thus the StackOverflowError

The code will end up in an infinite loop. !!! That's why the your stack get filled.!!
Fix :
Remove the
DriverManager.getConnection(String_url,USER,PASS);
called from the getConnection function will again call the same function. So remove that from getConnection function

Your call
dbConnection = DriverManager.getConnection(String_url,USER,PASS);
creates an endless recursion. You are importing java.sql.* but nonetheless your call calls getConnection() in your class.
Change to
dbConnection = java.sql.DriverManager.getConnection(String_url,USER,PASS);

Related

Error in insert data using keyboard on JDBC

In JDBC, I want to insert data using input from the keyboard.
As a result of finding the method, I came to know the scanner and wrote the code as follows.
package DB;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;
class insert{
Connection con;
Statement stmt;
Scanner scan = new Scanner(Syetem.in);
public insert() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#localhost:1521:orcl";
con = DriverManager.getConnection(url,"scott","1234");
stmt = con.createStatement();
} catch(ClassNotFoundException ce) {
System.out.println(ce.getMessage());
} catch(SQLException se){
System.out.println(se.getMessage());
}
}
public void disconnect() throws SQLException{
if (stmt!=null) stmt.close();
if (con!=null) con.close();
}
public void insert() throws SQLException{
System.out.println("name:")
String employee_name=scan.next();
System.out.println("domain:")
String street=scan.next();
System.out.println("country:")
String city=scan.next();
String sql="insert into information values('"+name+"', '"+domain+"', '"+country+"')";
int n=stmt.executeUpdate(sql);
}
}
But it didn't run and got an error ...
The default method cannot be found in the class. Define a default method in the following format. public static void main (String [] args)
Where should I put the main function to fix the error?
What is the problem? The name of the table to be inserted is 'information'.
Any help would be greatly appreciated
Because JDBC is not yet familiar, if possible, if you write a full query including a connection as in the above query, I would be very grateful.
*my oracle version is 11g
For your code to run you need to provide a method that works as an entry point for your program, that method has the signature public static void main(String[] args) besides that, your class should be named Insert with capital I first because thats de standard y second because you have a method called insert, you will need to have something like this:
public class Insert {
public Insert() {
...
}
public void disconnect() throws SQLException {
...
}
public void insert() throws SQLException {
...
}
public static void main(String[] args) {
new Insert().insert();
}
}

Java Class.forName() not working, class string loaded from property file

I have a simple Java project in Eclipse, which can connect to several databases, and am trying to modify it to allow configuration of connection parameters from property file.
At current stage, I have a working DBHelper class, which provides a getDatabaseConnection() method returning a Connection item instantiated using hard coded parameters.
I am trying to create a similar class, which does the same but reads parameters from property file.
It is called PropertyParser and provides getDBConnection() method.
The fact is that Class.forName() method fails if called from this latter, even if all connection data saved in property file are exactly the same hard coded in DBHelper class, and both refer to the full class name (oracle.jdbc.driver.OracleDriver).
Here follows my code.
Old working class:
package mypath.helpers;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBHelper {
public static Connection getDatabaseConnection(){
String dbClass = "oracle.jdbc.driver.OracleDriver";
String dbUrl = "jdbc:oracle:thin:#host:port/service";
String dbUser = "user";
String dbPass = "pass";
// connect to DB
try {
Class.forName(dbClass);
Connection con = DriverManager.getConnection(dbUrl, dbUser, dbPass);
con.setAutoCommit(false);
return con;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
New not working class:
package mypath.helpers;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class PropertyParser extends Properties{
// variables
private static String propFile = "conf/myprops.properties";
private static String dbClassProp = "DBCLASS";
private static String dbUrlProp = "DBURL";
private static String dbUserProp = "DBUSER";
private static String dbPassProp = "DBPASS";
// constructor
public PropertyParser() throws FileNotFoundException, IOException{
super();
this.load(new FileInputStream(propFile));
}
public Connection getDBConnection() throws SQLException, ClassNotFoundException{
// read properties
String JDBCClass = this.getProperty(dbClassProp).trim() ;
String JDBCUrl = this.getProperty(dbUrlProp).trim();
String JDBCUserId = this.getProperty(dbUserProp).trim();
String JDBCPasswd = this.getProperty(dbPassProp).trim();
Class.forName(JDBCClass);
Connection con = DriverManager.getConnection(JDBCUrl, JDBCUserId, JDBCPasswd);
con.setAutoCommit(false);
return con;
}
}
And here's the main, whith both calls:
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException {
// this works fine
Connection con = DBHelper.getDatabaseConnection();
System.out.println("Everything works fine till now.");
// this does not work
PropertyParser pp = new PropertyParser();
Connection con2 = pp.getDBConnection();
System.out.println("I will never reach this point.");
}
And here's the output i get:
Everything works fine till now.
Exception in thread "main" java.lang.ClassNotFoundException: "oracle.jdbc.driver.OracleDriver"
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at mypath.helpers.PropertyParser.getDBConnection(PropertyParser.java:35)
at mypath.GetConnection.main(GetConnection.java:20)
ojdbc.jar file is configured in the build path of the project. Is there a way to accomplish the result?
Double quotes.
You don't have to put double quotes in properties values.
so its:
DBCLASS=oracle.jdbc.driver.OracleDriver
and not
DBCLASS="oracle.jdbc.driver.OracleDriver"
The problem is shown in the expection message:
Exception in thread "main" java.lang.ClassNotFoundException: "oracle.jdbc.driver.OracleDriver"
If I write
Class.forName("HelloWorld");
I get the following exception message:
Exception in thread "main" java.lang.ClassNotFoundException: HelloWorld
Somehow your properties file contains not the class name, but the class name enclosed in quotes.
Strip of those quotes and your code will work.
See if there is an oracle.jdbc.driver.OracleDriver class in ojdbc.jar.
In simple ways, it is an import for the class with the fully qualified name oracle.jdbc.driver.OracleDriver and see is it report an error in your eclipse.

why No suitable driver found for mysql message here?

this is my code snippet,
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class Delete
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("mysql:jdbc://localhost:3306/raja","root","459805");
Statement stmt=con.createStatement();
int count=stmt.executeUpdate("DELETE GENNU WHERE USER_ID=3;");
if(count>0)
System.out.println(" Ok Deletion done");
}
catch(ClassNotFoundException e)
{
System.out.println(e.getMessage());
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
}
and when I execute it , i got like this.
actually you have an error in your DELETE statement, you lack FROM keyword. it should be
DELETE FROM GENNU WHERE USER_ID=3
see the error, it's pointing on DELETE.
UPDATE 1
try, jdbc:mysql not mysql:jdbc
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/raja"
+ "user=root&password=459805");
MySQL and JAVA JDBC
Try with
Class.forName("com.mysql.jdbc.Driver").newInstance();
The documentation says:
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
Also, the URL should be
jdbc:mysql://localhost/3306/raja
and not
mysql:jdbc://localhost/3306/raja
You need the mySQL Java Connector. Which you can find at the download page here:
https://www.mysql.com/products/connector/

how to to connect and use JDBCUtil

hi
i want to use Class JDBCUtil in java language and eclips workspace and I have the below code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCUtil {
static final String CONN_STR = "jdbc:hsqldb:hsql://localhost/";
static {
try {
Class.forName("org.hsqldb.jdbcDriver");
} catch (ClassNotFoundException ex) {
System.err.println("Unable to load HSQL JDBC driver");
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(CONN_STR);
}
}
but when I run it, I get the below Exception:
Unable to load HSQL JDBC driver
Exception in thread "main" java.lang.NullPointerException
at domain.EnrollCtrl.getCurrentOfferings(EnrollCtrl.java:78)
at ui.UI.main(UI.java:28)
in addition there is UI and EnrollCtrl and another file in this project but the error is in this path.
how can i fix this error? should I do sth for connectin to jdbc:hsqldb:hsql://localhost/?
thank U
your String CONN_STR = "jdbc:hsqldb:hsql://localhost/"; should be
conn = DriverManager.getConnection(jdbc:hsqldb:hsql://localhost/xdb", "sa", "");
In some circumstances, you may have to use the following line to get the driver.
Class.forName("org.hsqldb.jdbcDriver").newInstance();
The chances are that you are missing the hsqldb.jar file from your classpath or some other environmental issue.
It is difficult to be certain as your question is incredibly specific to your code and environment.

Jdbcrowset bug ? return nullpointer exception!

package CrimeFile;
import com.sun.rowset.JdbcRowSetImpl;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.rowset.JdbcRowSet;
/**
*
* #author singgum3b
*/
public class test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
// TODO code application logic here
JdbcRowSet jrsi=new JdbcRowSetImpl();
jrsi.setUrl("jdbc:sqlserver://localhost:1433;databaseName=CrimeFile");
jrsi.setUsername("sa");
jrsi.setPassword("hellokitty");
jrsi.setCommand("select * from dbo.Target");
jrsi.execute();
}
catch (SQLException ex) {
Logger.getLogger(test.class.getName()).log(Level.ALL, null, ex);
}
}
}
Exception:
Exception in thread "main" java.lang.NullPointerException
at com.sun.rowset.JdbcRowSetImpl.prepare(JdbcRowSetImpl.java:666)
at com.sun.rowset.JdbcRowSetImpl.execute(JdbcRowSetImpl.java:553)
at CrimeFile.test.main(test.java:30)
Java Result: 1
(line 30 is crsi.excute();)
I'm using sql server 2008 and ms jdbc 3.0.I googling around and found out this code is the same as in Sun's example link .Am i wrong?
I was having the same problem and came to conclusion that the problem is that Microsoft driver doesnt support combination of conn.prepareStatemen(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); as stated
at microsoft website
resulting in exception of prepare() method.
I took source code from here created my own MyJdbcRowSetImpl and changed parameter of prepareStatement to ResultSet.TYPE_SCROLL_SENSITIVE
Jtds driver wasnt solution as it doesnt support rowsets.
Ok, the answer was to switch to JtDS driver, which can be found here
There's clearly something bollixed up in MS JDBC driver.
I remember this NullPointerException happening to me but only if I call execute() when I should NOT be doing so i.e. when using JdbcRowSetImpl with a ResultSet as argument
private JdbcRowSet executeWithResultSet(Connection conn, String sqlQuery)
throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlQuery);
JdbcRowSet jdbcRs = new JdbcRowSetImpl(rs);
jdbcRs.execute(); //<-- results to the error as reported
return jdbcRs;
}

Categories

Resources