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

方法一:ODBC连接(用于本机测试)常用Jdbc—Odbc桥连接

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

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

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png

配置成功之后

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值