精通Java核心技术源代码
源代码在线查看: dbconnection.java
// ==================== Program Discription ==========================
// 程序名称:示例13-1 : DBConnection.java
// 程序目的:建立数据库连接
// ==============================================================
import java.sql.*;
public class DBConnection
{
// 指定驱动程序
private static String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
// 创建指定数据库的URL
private static String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test";
// 提供用户名和密码
private static String user="sa";
private static String password="sasa";
public static Connection getConnection() {
Connection con;
try {
//加载驱动程序
Class.forName(driver);
//创建连接
con = DriverManager.getConnection(url, user, password);
return con;
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return null;
}
}