1 // ==================== Program Description ==========================
2 // 程序名称:示例13-1 : DBConnection.java
3 // 程序目的:建立数据库连接
4 // ==============================================================
5 import java.sql.*;
6
7 public class DBConnection
8 {
9 // 指定驱动程序
10 private static String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
11 // 创建指定数据库的URL
12 private static String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test";
13 // 提供用户名和密码
14 private static String user="sa";
15 private static String password="sasa";
16
17 public static Connection getConnection() {
18 Connection con;
19 try {
20 // 加载驱动程序
21 Class.forName(driver);
22 // 创建连接
23 con = DriverManager.getConnection(url, user, password);
24 return con;
25 } catch (ClassNotFoundException e) {
26 System.out.println(e.getMessage());
27 } catch (SQLException e) {
28 System.out.println(e.getMessage());
29 }
30 return null;
31 }
32 } |