简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM