您的位置:首页 > 编程语言 > Java开发

[原]Java web学习系列之 Java web开发中数据库连接几种方法

2014-10-23 21:04 681 查看
方法一:ODBC连接(用于本机测试)常用Jdbc—Odbc桥连接

该方法首先要配置数据源。开始—控制面板—性能和维护—管理工具—数据源

点击“添加”,然后选中SQLsever,

















配置成功之后

public class DBConnection{
     //数据库连接驱动包
   private static final String DRIVER="sun.jdbc.odbc.JdbcOdbcDriver";
    //URL 地址
  private static final String URL="jdbc:odbc:Demo";
  public Connection getconn() throws ClassNotFoundException, SQLException{
           //加载驱动
           Class.forName(DRIVER);
          //建立连接
           Connection con=DriverManager.getConnection(URL);
           return con;
 }
 public void close(Connection con,Statement statement,ResultSet resultSet) throws
SQLException{
           //关闭数据库连接,遵循进栈、出栈原理,后进先出
                 if(resultSet!=null)
              {
                   resultSet.close();
             }
                 if(statement!=null)
              {
                    statement.close();
              }
             if(con!=null)
             {
                con.close();
             }  
  }
}


第二种方式:Jdbc连接,比较常用的方式,不用配置数据源,只需加载驱动包即可

public class BaseDAO {
 //数据库连接驱动包
 private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
 //URL 地址
 private static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=Students";
 //连接数据库的用户名
 private static final String USER = "sa";
 //连接数据库的密码
 private static final String PWD = "sasa";
 
 public Connection getCon() throws ClassNotFoundException, SQLException{
       
     Class.forName(DRIVER);
  
     Connection con = DriverManager.getConnection(URL,USER,PWD);
    
     return con;
 }
 
 public void closeAll(Connection con, Statement st, ResultSet rs) throws SQLException{
         
       if(rs != null)
        {
          rs.close();
        }
      if(st != null)
        {
          st.close();
        }
     if(con != null)
       {
        con.close();
        }
  }
}


方法三:外部资源加载

db.properties外部资源文件
 driver = com.microsoft.sqlserver.jdbc.SQLServerDriver;
 
 url = jdbc:sqlserver://localhost:1433;databaseName=Students;
 user= sa;

 pwd= sasa;

用外部资源包导入驱动:
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
  //以文件流的方式加载外部资源文件
  FileInputStream fileinstream = new FileInputStream("db.properties");
  
  Properties properties = new Properties();
  properties.load(fileinstream);
  String driver = properties.getProperty("driver");
  String url = properties.getProperty("url");
  String user = properties.getProperty("user");
  String pwd = properties.getProperty("pwd");
  
  Class.forName(driver);
  Connection con = DriverManager.getConnection(url,user,pwd);
  System.out.println("Connect ok !");
  
 }


以上即为Java应用程序与数据库连接的常用的三种方法!

笔记记于 2010-8-24
15:41
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: