第一种:
public class DBTest {
public static void main(String[] args) {
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://localhost:1433";
String username = "sa";
String password = "";
try {
Class.forName(driver);
System.out.println("数据库驱动程序注册成功");
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("成功连接数据库");
}
catch (Exception e) {
System.out.println("数据库连接失败");
e.printStackTrace();
}
}
}
第二种:
public class DBTest {
private static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static String url = "jdbc:sqlserver://localhost:1433";
private static String username = "sa";
private static String password = "";
private Connection con ;
public DBTest()throws IOException{
try{
Class.forName(driver);
con = java.sql.DriverManager.getConnection(url,username,password);
}catch(Exception e){ e.printStackTrace();}
}
public static void main(String[] args){
DBTest test = new DBTest();
Connection con = test.con;
try{
Class.forName(driver);
con = java.sql.DriverManager.getConnection(url,username,password);
}catch(Exception e){}
}