Null Pointer Exception while executeUpdate for a query using JDBC - java

I am getting a Null Pointer Exception while executing the insert query. Everything seems to be fine but the problem still exists.
Code used for Database Connection.
public class DBConnect
{
static Connection c ;
static Statement st ;
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
c=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","ashuthesmartest","ashutosha");
st=c.createStatement();
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Database error");
}
}
}
Action Performed on Button Click
private void b3ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
char[] arr = pa1.getPassword() ;
String s2 = Arrays.toString(arr) ;
String s1 = t3.getText() ;
DBConnect.st.executeUpdate("insert into LOGIN values('"+s1+"','"+s2+"')"); **//EXCEPTION IN THIS LINE**
}
catch (Exception ex)
{
ex.printStackTrace();
}
}

The initialization block in which you create the connection and the statement is not a static initialization block.
Therefore, it will only be executed when you create an instance of the class DBConnect.
Since you seem to be using DBConnect only statically, that never happens. Your initialization block should be made static. A static initialization block has the keyword static preceding the left brace:
static {
// try etc.
}

Related

Java and SQL Server

I am new to java, and I am trying to create a method that will retrieve information from the database based on the query that will pass to it.
I thought that I could create by method by creating an object of type:
private Connection controlTableConnection = null;
and then
Statement statement = controlTableConnection.createStatement();
but when I do that piece of code, I get a highlight error:
Unhandled exception
Any help, would be appreciated.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class ConnectMSSQLServer {
private static final String db_connect_string = "jdbc:sqlserver://Cdsx\\SQxxs";
private static final String db_userid = "aa";
private static final String db_password = "bb";
private Connection controlTableConnection = null;
public void dbConnect() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection controlTableConnection = DriverManager.getConnection(db_connect_string, db_userid, db_password);
} catch (Exception e) {
e.printStackTrace();
}
}
public void dbDisconnect() {
try {
if (controlTableConnection != null && !controlTableConnection.isClosed()) {
controlTableConnection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void createstatement() {
Statement statement = controlTableConnection.createStatement();
}
}
You have to wrap the createStatement line like below, as you have to handle the SQLException.
try {
Statement statement = controlTableConnection.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
isn't the Connection null? Do you have a driver on the classpath? is the default port correct? Is the sql server live? What kind of exception do you get exactly?
You need to post at least the stack trace or logs

Java : How to ignore some SQLException?

I'm trying to drop some objects in Oracle database using jdbc. I want to skip if specific ORA-04043 error occurs. The followings are the code I built.
This array string variable is SqlList.uninstall_OS_COMMAND_SQL.
public static String[] uninstall_OS_COMMAND_SQL = {
"DROP PACKAGE OS_COMMAND",
"DROP PACKAGE LOB_WRITER_PLSQL",
"DROP TYPE OSCOMMAND_VC2_ARRAY",
"DROP TYPE OSCOMMAND_DIR_ARRAY",
"DROP TYPE OSCOMMAND_DIR_ENTRY",
"DROP TYPE FILE_LIST_TYPE",
"DROP TYPE FILE_TYPE",
"DROP PACKAGE FILE_PKG",
"DROP JAVA SOURCE \"OS_HELPER\"",
"DROP JAVA SOURCE \"FILE_TYPE_JAVA\"",
"DROP PACKAGE FILE_SECURITY"
};
and this is the code.
private void uninstallOS_COMMAND_Step1_For_11g() {
Connection targetDBconn = null;
Statement stmt = null;
try {
targetDBconn = globalTargetConn.connect();
logWriter.writeLogs(logTextArea, LogWriter.INFO, "Uninstalling OS_COMMAND package...");
for (int i = 0; i < SqlList.uninstall_OS_COMMAND_SQL.length; i++) {
stmt = targetDBconn.createStatement();
stmt.setEscapeProcessing(false);
logWriter.writeLogs(logTextArea, LogWriter.INFO, "See the query below...");
logWriter.writeLogs(logTextArea, LogWriter.INFO, "\n"+SqlList.uninstall_OS_COMMAND_SQL[i]);
stmt.executeUpdate(SqlList.uninstall_OS_COMMAND_SQL[i]);
}
} catch (SQLException ex) { logWriter.writeLogs(logTextArea, LogWriter.ERROR, ex.getMessage());
} finally {
if (stmt != null ) try {stmt.close();} catch(SQLException ex) {}
if (targetDBconn != null ) try {targetDBconn.close();} catch(SQLException ex) {}
}
}
If I run this code, it executes just one item in the array and stops the entire method. Please help me..
Create one new method and call the new method inloop
Like
execute(Statement stmt, SQL Command ) throws Exception {
try {
stmt.executeUpdate(SqlList.uninstall_OS_COMMAND_SQL[i]);
} catch(SQLException s) {
//LOG error
if (s.getMessage().contains("ORA-04043")) {
} else {
throw s;
}
} catch (Exception ee) {
throw ee;
}
}
you might consider to put your try and catch inside the loop.

The static method getDBConnection() from the type DBConnection should be accessed in a static way

I have got a singleton class as shown below for accessing Database connection as
public class DBConnection {
private static volatile DBConnection instance;
private static DataSource dataSource;
private DBConnection(){
}
public static synchronized DBConnection getInstance() {
if (instance == null) {
instance = new DBConnection();
}
return instance;
}
static {
try {
dataSource = (DataSource) new InitialContext()
.lookup("java:comp/env/jdbc/MySQLDataSource");
} catch (NamingException e) {
e.printStackTrace();
try {
throw new Exception("'jndifordbconc' not found in JNDI", e);
} catch (Exception e1) {
logger.error("Error description", e);
}
}
}
public static Connection getDBConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
logger.error("Error description", e);
return null;
}
}
}
And when i am trying to access the DBConnection this way
SeperateClass
Here i am getting the yellow warning
public String fetchGlobalIndicesData(#QueryParam("region_name") String region_name )
{
Connection dbConnection = null;
String selectsql = "";
try
{
dbConnection = DBConnection.getInstance().getDBConnection();
selectpstmt = dbConnection.prepareStatement(selectsql);
selectpstmt.setString(1, region_name);
selectRset = selectpstmt.executeQuery();
}
catch (Exception e)
{
logger.error("Error description",e);
}
}
Eclipse IDE is giving me a yellow warning saying
The static method getDBConnection() from the type DBConnection should be accessed in a static way
Could you please tell me whats the proper way of doing this ??
I modified my code as
public static Connection getDBConnection() {
try {
return getInstance().dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
logger.error("Error description", e);
return null;
}
}
Since it is static, you are supposed to call the method directly on the class , not on an instance of the class :
DBConnection.getDBConnection()
Calling the method on an instance has no sense, though it is possible.
As #Berger mentioned, you defined the method as static, so you have to call it as he mentioned.
If you don't want it static, you can modify your code by removing static from the getDBConnection method and call it as:
DBConnection.getInstance().getDBConnection()
The code above is already correct in your fetchGlobalIndicesData method.
Just for the sake of it:
public static Connection getDBConnection()
Becomes:
public Connection getDBConnection()
This way, getInstance will initialize a DBConnection instance, and the static initializer block to init your datasource should fire. Then when you call getDBConnection, your code should work fine.
That is an static method, you can remove the static keyword of the getDBConnection() signature or use DBConnection.getDBConnection()

NullPointerException - Using Java to Execute SQL

I have the following Code that throws a null pointer exeption
public void checkAcc(String sql)
{
System.out.print(sql); // the statement executed is "SELECT AccountID FROM BankAccount"
try {
stmt.executeQuery(sql);
} catch (Exception e) {
System.err.println("Nope that is broken - " + e);
}
}
Have you checked to ensure that stmt isn't null? The way that function is written, it must be a field, and you have to make certain that it has been initialized before checkAcc() is called.

Nullpointer Exception (Derby, JDBC)

Hy!!
My error code:
Exception in thread "main" java.lang.NullPointerException
at lesebank.Konto.getKontofromID(Konto.java:39)
at lesebank.Main.main(Main.java:18)
SQL EXCEPTIONJava Result: 1
BUILD SUCCESSFUL (total time: 1 second)
Method:
Konto konto = new Konto ();
Statement s = dbconn.getSt();
try
{ //in the next line the error occurs
s.execute("select id,inhaberin,ktostd,habenzinsen,notiz from Konto where id = " +id);
ResultSet set = s.getResultSet();
if (set.next())
{
konto.setId(set.getInt(1));
konto.setId_inhaberin(set.getInt(2));
konto.setKtostd(set.getDouble(3));
konto.setHabenzinsen(set.getDouble(4));
konto.setNotiz(set.getString(5));
return konto;
}
}
catch (SQLException ex)
{
System.out.print(ex.getMessage());
}
return null;
DBConn:
public class DBConnection {
private String url = "jdbc:derby://localhost:1527/Bank";
private Connection conn;
private Statement st;
public DBConnection() {
try
{
conn = DriverManager.getConnection(this.url, "test", "test");
st = conn.createStatement();
}
catch (SQLException ex)
{
System.out.print("SQL EXCEPTION");
}
}
public Statement getSt() {
return st;
}
Database:
Please help
This is Very Bad(tm):
public DBConnection() {
try
{
conn = DriverManager.getConnection(this.url, "test", "test");
st = conn.createStatement();
}
catch (SQLException ex)
{
System.out.print("SQL EXCEPTION");
}
}
Do not catch and ignore exceptions like this. There are there for a very good reason. In this case, if your constructor fails due to an exception, the whole DbConnection object is rendered useless, since the st field will be null. Yet because the code that instantiated DbConnection has no idea this has happened, you go on to use it, and end up with the null-pointer exception.
If DbConnection's constructor triggers an exception, you need to throw that exception out of the constructor, forcing your code to deal with the exception:
public class DBConnection {
private static final String URL = "jdbc:derby://localhost:1527/Bank";
private final Connection conn;
private final Statement st;
public DBConnection() throws SQLException {
conn = DriverManager.getConnection(URL, "test", "test");
st = conn.createStatement();
}
public Statement getSt() {
return st;
}
}
Note also the final fields. This gives you a compile-time guarantee that something will be assigned to those fields.
Please check that dbconn.getSt() is not returning null. What is getSt(), anyway; anything like createStatement()? Now that I see your edit, it is likely that your DBConn class is not successful in its call to createStatement().
Not quite able to test right now, but I would sugest you make your DBConnection.getSt() method return a brand new Statement object, instead of reusing the same one over and over. Would be something like:
public Statement getSt() {
return conn.createStatement();
}
Remember to close your statement after using it.

Categories