Will
Will

Reputation: 49

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


}

Upvotes: 1

Views: 69

Answers (2)

user6622043
user6622043

Reputation: 101

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

Upvotes: 0

lsiva
lsiva

Reputation: 485

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

Upvotes: 3

Related Questions