user2708377
user2708377

Reputation: 55

Confused about how to connect sqlserver via JDBC

This is my first java application I have been trying to connect to sql and get some records for three hours.I dont get any execptions or errors.but nothing displayed so far.I am not sure if am i connected or not

           public static  void main(String[]args) throws ClassNotFoundException 
           ,SQLException{


  String url = "jdbc:sqlserver://.\\SQLEXPRESS;databaseName=Northwind; Integrated   Security=SSPI";  
         Integrated Security=SSPI";

         Connection con=null;
         Statement stmt=null;

         ResultSet rs=null;
         try {
             Class.forName("com.microsoft.sqlserver.jdbc.SqlServerDriver");

             con=DriverManager.getConnection(url);
             String sql="Select Top 3 from * person.Contact";
             stmt=con.createStatement();
             rs=stmt.executeQuery(sql);
             while(rs.next()){
             System.out.println(rs.getString(1));



             }
              }

         catch ( Exception e) {
             e.printStackTrace();
    }

  }

Upvotes: 0

Views: 132

Answers (2)

KhAn SaAb
KhAn SaAb

Reputation: 5376

you can figure out your issue by throwing exception or by Exception handling by try catch

public static  void main(String[]args)throws SQLException,ClassNotFoundException

or by stackTrace()

 catch (Exception e) {
         e.printStackTrace();
}

forName() throws ClassNotFoundException and getConnection() throws SQLException

Upvotes: 0

Reimeus
Reimeus

Reputation: 159854

Try displaying the stacktrace

try {
  ...
} catch (SQLException e) {
   e.printStackTrace();
}

Upvotes: 2

Related Questions