The following is the code that checks SQL Server can successfully connect.
Take a change, you can also be used for other database connections.
Import java.sql. *;
Public class test {
Public static void main (String [] args) {
String driverclassname = "com.microsoft.jdbc.sqlserver.sqlserdriver";
String URL = "JDBC: Microsoft: SQLServer: //127.0.0.1: 1433; DatabaseName = Northwind";
String uid = "sa";
String PWD = "sa";
Try {
Class.Forname (driverclassname);
} catch (exception e) {
E.PrintStackTrace ();
System.err.Println ("Can't find the driver path.");
System.exit (0);
}
Connection conn = NULL;
PreparedStatement PS = NULL;
ResultSet RS = NULL;
String SQL = "Select * from categories";
Try {
CONN = DriverManager.getConnection (URL, UID, PWD);
PS = conn.preparestatement (SQL);
RS = ps.executeQuery ();
System.out.println ("Table Categories:");
System.out.println ("ID / T / TNAME");
While (rs.next ()) {
String ID = rs.getstring ("categoryid");
String name = rs.getstring ("categoryName");
System.out.println (ID "/ T / T" Name);
}
} catch (sqlexception e) {
E.PrintStackTrace ();
System.err.Println ("Connection Database Fails.");
System.exit (0);
} finally {
IF (rs! = null) {
Try {
Rs.close ();
} catch (sqlexception e) {
E.PrintStackTrace ();
System.err.println ("You cannot close the database connection");
System.exit (0);
}
}
IF (ps! = null) {
Try {
ps.close ();
} catch (sqlexception e) {
E.PrintStackTrace ();
System.err.println ("You cannot close the database connection");
System.exit (0);
}
}
IF (conn! = null) {
Try {
CONN.CLOSE ();
} catch (sqlexception e) {
E.PrintStackTrace ();
System.err.println ("You cannot close the database connection");
System.exit (0);
}
}
}
System.out.println ("Database connection test is successful.");
}
}