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();
 }
}
azurefrog
11k7 gold badges45 silver badges56 bronze badges
asked Jul 22, 2016 at 19:38

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();
 }
answered Jul 22, 2016 at 19:45
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

answered Jul 22, 2016 at 20:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.