1

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


}

2 Answers 2

3

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();
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.