日期:2014-05-17 浏览次数:20755 次
package tools; import java.sql.*; public class JDBConnection { private final String dbDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; //连接sql数据库的方法 private final String url = "jdbc:sqlserver://localhost:1433;DatabaseName=数据库名称"; private final String userName = "sa"; private final String password = "sa"; private Connection con = null; public JDBConnection() { try { Class.forName(dbDriver).newInstance(); //加载数据库驱动 con = DriverManager.getConnection(url, userName, password); con.setAutoCommit(true); System.out.println("数据库连接成功!"); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println("创建数据库连接出错!"); } } //关闭数据库的操作 public void closeConnection() { try { if(con!=null) con.close(); } catch (SQLException e) { e.printStackTrace(); System.out.println("关闭数据库失败!"); } } public Connection getCon() { return con; } }