代码改变世界

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

  雪夜&流星  阅读(784)  评论(0编辑  收藏  举报

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

编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示