Unable to Execute a sql query on java using jdbc

I am learning JDBC and trying to execute sql query on Java using IDE Eclipse. The jdbc driver is getting loaded and the connection is getting established, however the query doesn't run.

import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
    String url="jdbc:oracle:thin:@//localhost:1521/xe";
    String un="system";
    String pwd="system";
    Connection con=null;
    Statement stmt=null;
    ResultSet res=null;
    try{
        DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
        System.out.println("Driver Loaded successfully");
    }
    catch(Exception e)
    {
        System.out.println("Driver not loaded");
    }
    try{
        DriverManager.getConnection(url,un,pwd);
        System.out.println("Connection established");
    }
    catch(Exception f)
    {
        System.out.println("Connection not established");
    }
    try{
        String s="Select * from student";
        stmt=con.createStatement();
        res=stmt.executeQuery(s);
        System.out.println("Query executed succesfully");
    }
    catch(Exception e)
    {
        System.out.println("Query not executed");
    }  

Output is : Driver Loaded successfully

Connection established

Query not executed


You are getting exception because you have not initialized your Connection reference you have declared.

Modify your DriverManager.getConnection(...) as follows:

con = DriverManager.getConnection(...) .

Let me know if it helps.


Another way to view how the OP was able to have this issue. Initializing variables unnecessarily can let you forget to set them correctly. It defeats the compiler checks that all locals are set before being used.

Connection con=null;
try {
    con = ...;
    ...;
} finally {
    if(con != null) con.close();
}

This would have more compiler checks as:

Connection con = ...;
try {
    Statement stmt = con...;
    try {
        ResultSet rst = stmt...;
        try {
            ...;
        } finally {
            rst.close();
        }
    } finally {
        stmt.close();
    }
} finally {
    con.close();
}

Or, in Java 1.7+:

try (
    Connection con = ...;
    Statement stmt = con...;
    ResultSet res = stmt...;
) {
   ...;
}

Please see Java Practices -> Don't declare local variables before use for futher reading.

链接地址: http://www.djcxy.com/p/94256.html

上一篇: 放大故事板中的任何视图时,Xcode 8.2和8.1崩溃

下一篇: 无法使用jdbc在java上执行sql查询