zoukankan      html  css  js  c++  java
  • [原]Java web学习系列之 Java web开发中数据库连接几种方法

    方法一: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

  • 相关阅读:
    div的自动滚动
    异步发送添加请求的客户端实现
    asp.net防止一个用户登录多次的方法
    asp.net ajax动态显示时间
    也谈Javascript的效率,createElement和innerHTML,为innerHTML平反
    精妙MSSql语句
    看看国外做的js效果
    prototype.js常用函数及其用法
    PPTP 服务器配置
    Linux date 命令使用技巧
  • 原文地址:https://www.cnblogs.com/tanlon/p/2371358.html
Copyright © 2011-2022 走看看