使用jdbc操作Oracle数据库
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
使用jdbc操作Oracle数据库
来源:开发界
使用jdbc操作数据库步骤是固定的
1.将驱动包导入到数据库,每一个数据库的驱动包都不一样,下面我提供一个Oracle数据库的驱动包将它下载后放入web项目中的web-inf中的lib中
2.选择项目右键,选择Build Bath,在libraries中add JARs,选择刚才的jar包
3.余下步骤示例如下:
public class NewsDao {
/**
* @param args
*/
//查询新闻信息
public void getNewsList(){
Connection connection=null;
Statement stmt=null;
ResultSet rs=null;
try {
//(1)()加载驱动
//(2)(URL,用户名,密码)获得数据库连接(Connection)
connection=("jdbc:oracle:thin:@localhost:1521:news","news_dev_u","news");
//(3)获得Statement对象,执行SQL语句
String sql="select * from news_detail";
stmt=();
rs=(sql);
//(4)处理执行结果(ResultSet),
while()){
int id=("id");
String title=("title");
String summary=("summary");
String content=("content");
String author=("author");
Timestamp time=("createdate");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
();
} catch (SQLException e) {
// TODO Auto-generated catch block
();
}finally{
//释放资源
try {
();
();
();
} catch (SQLException e) {
// TODO Auto-generated catch block
();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
NewsDao newsDao=new NewsDao();
();
}
}
public class NewsDao {
/**
* @param args
*/
//查询新闻信息
public void getNewsList(){
Connection connection=null;
Statement stmt=null;
ResultSet rs=null;
try {
//(1)()加载驱动
//(2)(URL,用户名,密码)获得数据库连接(Connection)
connection=("jdbc:oracle:thin:@localhost:1521:news","news_dev_u","news");
//(3)获得Statement对象,执行SQL语句
String sql="select * from news_detail";
stmt=();
rs=(sql);
//(4)处理执行结果(ResultSet),
while()){
int id=("id");
String title=("title");
String summary=("summary");
String content=("content");
String author=("author");
Timestamp time=("createdate");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
();
} catch (SQLException e) {
// TODO Auto-generated catch block
();
}finally{
//释放资源
try {
();
();
();
} catch (SQLException e) {
// TODO Auto-generated catch block
();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
NewsDao newsDao=new NewsDao();
();
}
}
同时我们也可以把这些数据库配置数据放入一个配置文件中,例如我创建了一个文件在src中这样修改数据库信息就可以在配置文件中操作,读取配置文件方法如下:
//读取配置文件(属性文件)的工具类
public class ConfigManager {
private static ConfigManager configManager;
//(InputStream);读取属性文件
private static Properties properties;
private ConfigManager(){
String configFile="";
properties=new Properties();
try {
(in);
();
} catch (IOException e) {
// TODO Auto-generated catch block
();
}
}
public static ConfigManager getInstance(){
if(configManager==null){
configManager=new ConfigManager();
}
return configManager;