Link to home
Start Free TrialLog in
Avatar of Peter Chan
Peter ChanFlag for Hong Kong

asked on

Issue to connect

Hi,
I have no issue to connect to SQL server, having IP and port like

1??.?.?.?,59365

through SSMS. How to achieve the same, to change Java code below, to be able to connect to SQL server, in Java?

                  final String un = "casey";
                  final String pw = "****";
                  final String host = "jdbc:sqlserver://caseydid o\\mssqlex press:1433 ;databaseN ame=stock" ;

                  final String sql = "SELECT * FROM STAFF_DATA";
                  //loading the driver class
                  Class.forName("com.microso ft.sqlserv er.jdbc.SQ LServerDri ver"); //This is for driver sqljdbc2*
                  //   Class.forName("com.microso ft.jdbc.sq lserver.SQ LServerDri ver"); /*This is for driver sqljdbc4*/
                  final Connection conn = DriverManager.getConnection(un, pw, host);

Open in new window

Avatar of Qlemo
Qlemo
Flag of Germany image

Replace
final String host = "jdbc:sqlserver://caseydid o\\mssqlex press:1433 ;databaseN ame=stock" ;

Open in new window

with
final String host = "jdbc:sqlserver://1??.?.?.?:59365; databaseName=stock" ;

Open in new window

Avatar of Peter Chan

ASKER

Thanks a lot.
How to verify that even below is making fine to connect to SQL server database?
      public void doConnect(){
            try{
                  final String un = "casey";
                  final String pw = "****";
                  final String host = "jdbc:sqlserver://1?.?.?.?,59365;databaseName=acc_sch" ;

                  final String sql = "SELECT * FROM STAFF_DATA";
                  //loading the driver class
                  Class.forName("com.microso ft.sqlserv er.jdbc.SQ LServerDri ver"); //This is for driver sqljdbc2*
                  //   Class.forName("com.microso ft.jdbc.sq lserver.SQ LServerDri ver"); /*This is for driver sqljdbc4*/
                  final Connection conn = DriverManager.getConnection(un, pw, host);
                  final Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE );
                  final ResultSet rs = stmt.executeQuery(sql);
                  while (rs.next()){
                        System.out.println(rs.getString(1));
                        conn.close();
                  }

            } catch (final Exception ex) {
                  ex.printStackTrace();
            }
      }

Open in new window

How to adjust the above code?
If it works, it works!?
I mean how to adjust my current code to return message to see connection has been made successfully?
When doConnect succeeds it should return 0 - this indicates the connection was successful.

I would remove the while loop that prints the output and replace the statement with a simpler one (a lot of records in staff data may take a while).
Your problem is as people have implied above. Let me state it more plainly: your code doesn't really (just) do what it says it does. Yes, it makes a connection, but it then executes a query and then closes the connection after the first row. Why? What is it really meant to do?
Further observations.... your JDBC driver name has spaces in it that shouldn't be there...

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //This is for driver sqljdbc2*

Open in new window


And your new host string is still incorrect, you need a colon to separate the ip address from the port number, not a comma as you have it now, so ...

final String host = "jdbc:sqlserver://1?.?.?.?:59365;databaseName=acc_sch" ;
                                              ^

Open in new window

Thanks a lot Mccarl.
How to adjust the event to return a value, when there is a successful connection to database?
Just do something like this... (note: that I have moved the line where you close the connection to a more appropriate spot)

      public boolean doConnect(){
            try{
                  final String un = "casey";
                  final String pw = "****";
                  final String host = "jdbc:sqlserver://1?.?.?.?,59365;databaseName=acc_sch" ;

                  final String sql = "SELECT * FROM STAFF_DATA";
                  //loading the driver class
                  Class.forName("com.microso ft.sqlserv er.jdbc.SQ LServerDri ver"); //This is for driver sqljdbc2*
                  //   Class.forName("com.microso ft.jdbc.sq lserver.SQ LServerDri ver"); /*This is for driver sqljdbc4*/
                  final Connection conn = DriverManager.getConnection(un, pw, host);
                  final Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE );
                  final ResultSet rs = stmt.executeQuery(sql);
                  while (rs.next()){
                        System.out.println(rs.getString(1));
                  }
                  conn.close();
                  return true;
            } catch (final Exception ex) {
                  ex.printStackTrace();
                  return false;
            }
      }

Open in new window

Sorry to that I get
Description	Resource	Path	Location	Type
doConnect cannot be resolved to a variable	Main.java	/Dev0/appClientModule	line 46	Java Problem

Open in new window

with code below.

              if (doConnect)
            		  ...
      public boolean doConnect(){
            try{
                  final String un = "sa";
                  final String pw = "****";
                  final String host = "jdbc:sqlserver://??.?.?.?:59365;databaseName=acc_sch" ;

                  final String sql = "SELECT * FROM customer3";
                  //loading the driver class
                  Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //This is for driver sqljdbc2*
                  //   Class.forName("com.microso ft.jdbc.sq lserver.SQ LServerDri ver"); /*This is for driver sqljdbc4*/
                  final Connection conn = DriverManager.getConnection(un, pw, host);
                  final Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE );
                  final ResultSet rs = stmt.executeQuery(sql);
                  while (rs.next()){
                        System.out.println(rs.getString(1));
                        conn.close();
                  }
                  return true;

            } catch (final Exception ex) {
                  ex.printStackTrace();
                  return false;
            }
      }

Open in new window

doConnect is a method and so it needs to be called correctly like all methods...

 if (doConnect())

Open in new window

I still get

Description	Resource	Path	Location	Type
Cannot make a static reference to the non-static method doConnect() from the type Main	Main.java	/Dev0/appClientModule	line 46	Java Problem

Open in new window

to
              if (doConnect())

Open in new window

      public static boolean doConnect(){

Open in new window

Any idea to StackTrace below, from Connect event?
User generated image
You need to have the jar file containing the JDBC driver on the classpath.
Do you have relevant steps?
(note: that I have moved the line where you close the connection to a more appropriate spot)
But that makes it worse still. Not only is an irrelevant query being made, but this time every single row is being iterated and then discarded (instead of just one read and discarded)
HuaMin Chen, you didn't answer the questions i asked you
Sorry CEHJ.
Can you show with more details to adjust the event better? I expected to test the connection is fine vs DB>
I've no time now but just quickly - you should probably return type Connection (null if there's a problem). Get rid of the query
Yes, I can get rid of the query.

If available, can you also see the current issue encountered?
How to add jar file containing the JDBC driver on the classpath, to resolve issue below?
User generated image
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.