Will Will - 4 months ago 28
SQL Question

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();
}


}

Answer

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();
    }