import java.sql.*; public class TestConnect { public static void main(String []
ID: 3747556 • Letter: I
Question
import java.sql.*;
public class TestConnect {
public static void main(String [] args){
// Definitions for Microsoft (MS) SQL Server connection
String uri = "jdbc:sqlserver://theodore.ist.rit.edu;databaseName=Jobs";
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String user = "330User";
String password= "330Password";
// Connection object to database
Connection conn = null;
// Load the database driver
try {
Class.forName( driver );
System.out.println("Driver loaded");
}
catch( ClassNotFoundException cnfe ){
System.out.println("Cannot find or load driver "+driver);
cnfe.printStackTrace();
System.exit(1);
}
// Open the database
try{
conn = DriverManager.getConnection( uri, user, password );
System.out.println("Database open");
}
catch(SQLException sqle){
System.out.println("Could not connect to DB: "+uri);
sqle.printStackTrace();
System.exit(2);
}
// Close the database
try{
conn.close();
System.out.println("Database closed");
}
catch(SQLException sqle){
System.out.println("Could not close database");
sqle.printStackTrace();
System.exit(3);
}
} // end main
} // end TestConnect
Explanation / Answer
SQLServerDatabase.java
import java.sql.*;
public class TestConnect {
// Definitions for Microsoft (MS) SQL Server connection
private static String uri = "jdbc:sqlserver://theodore.ist.rit.edu;databaseName=Jobs";
private static String jdbc_driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static String user = "330User";
private static String password= "330Password";
// Connection object to database
private static Connection conn = null;
private static Driver driver;
public static boolean connect() throws SQLException{
if(driver == null){
try{
Class driverJdbcClass = Class.forName(jdbc_driver);
driver = (Driver) driverJdbcClass.newInstance();
DriverManager.register(driver);
DriverManager.getConnection(uri, user, password);
} catch(Exception e){
System.out.println("Failed to load jdbc driver");
return false;
}
}
return true;
} // end connect method
public static boolean close(Connection connection){
try{
if(connection != null)
connection.close();
} catch(SQLException sqle){
return false;
}
return true;
} // end close method
} // end TestConnect
Updated
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.