java_jdbc_oracle简单总结(2016-11-23)
JDBC连接oracle的实例
好久没写过jdbc,基本忘干净了,随意插一个图,简单学习一下。然后干别的。。。。。
使用jdbc操作数据库步骤是固定的
1.将驱动包导入到数据库,每一个数据库的驱动包都不一样,下面我提供一个Oracle数据库的驱动包http://download.csdn.net/detail/hncsy403/4530830将它下载后放入web项目中的 web-inf中的lib中
2.选择项目右键,选择Build Bath,在libraries中add JARs,选择刚才的jar包
学生类bean
package jdbc.bean; import java.util.Date; public class Student { private int id;
private String name;
private String password;
private String sex;
private int age;
private Date birthday;
private String memo;
private String photo;
private Date regTime; public int getAge() {
return age;
} public Date getBirthday() {
return birthday;
} public int getId() {
return id;
} public String getMemo() {
return memo;
} public String getName() {
return name;
} public String getPassword() {
return password;
} public String getPhoto() {
return photo;
} public Date getRegTime() {
return regTime;
} public String getSex() {
return sex;
} public void setAge(int age) {
this.age = age;
} public void setBirthday(Date birthday) {
this.birthday = birthday;
} public void setId(int id) {
this.id = id;
} public void setMemo(String memo) {
this.memo = memo;
} public void setName(String name) {
this.name = name;
} public void setPassword(String password) {
this.password = password;
} public void setPhoto(String photo) {
this.photo = photo;
} public void setRegTime(Date regTime) {
this.regTime = regTime;
} public void setSex(String sex) {
this.sex = sex;
} }
工具类:DBUtil
package jdbc.util; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class DBUtil { private static final String driverClass = "oracle.jdbc.driver.OracleDriver";
private static final String jdbcUrl = "jdbc:oracle:thin:@liumo:1521:ORCL";
private static final String user = "test_lm";
private static final String password = "test_lm"; public static Connection getConn() {
// 1.注册驱动
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} // 2.创建Connection(数据库连接对象)
Connection conn = null;
try {
conn = DriverManager.getConnection(jdbcUrl, user, password);
conn.setAutoCommit(false);
return conn;
} catch (SQLException e) {
e.printStackTrace();
}
/*
* Connection是Statement的工厂,一个Connection可以生产多个Statement。
* Statement是ResultSet的工厂,一个Statement却只能对应一个ResultSet(它们是一一对应的关系)。
* 所以在一段程序里要用多个ResultSet的时候,必须再Connection中获得多个Statement,然后一个Statement对应一个ResultSet。
*/
return null;
} /**
* 关闭连接(数据库连接对象)
* @param conn
*/
public static void close(Connection conn) {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
} /**
* 关闭编译的 SQL 语句的对象
* @param stmt
*/
public static void close(Statement stmt) {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
} /**
* 关闭结果集
* @param rs
*/
public static void close(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
} /**
* 提交事务
* @param conn
*/
public static void commit(Connection conn) {
try {
if (conn != null) {
conn.commit();
}
} catch (SQLException e) {
e.printStackTrace();
}
} /**
* 回滚事务
* @param conn
*/
public static void rollback(Connection conn) {
try {
if (conn != null) {
conn.rollback();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
实际的dao:StudentDao
package jdbc.dao; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import jdbc.bean.Student;
import jdbc.util.DBUtil; public class StudentDao { /**
* 保存
* @param student
*/
public void save(Student student) { Connection conn = DBUtil.getConn(); PreparedStatement pstmt = null;
String sql = " insert into t_student(name,password,sex,age,birthday,memo,photo,reg_time) ";
sql += " values(?,?,?,?,?,?,?,?) ";
try {
pstmt = conn.prepareStatement(sql); pstmt.setString(1, student.getName());
pstmt.setString(2, student.getPassword());
pstmt.setString(3, student.getSex());
pstmt.setInt(4, student.getAge());
pstmt.setDate(5, new java.sql.Date(student.getBirthday().getTime())); // 只存年月日这种形式
pstmt.setString(6, student.getMemo());
try {
// 构建一个输入流存blob
pstmt.setBlob(7, new FileInputStream(student.getPhoto()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
pstmt.setTimestamp(8, new java.sql.Timestamp(student.getRegTime().getTime())); // 完整的时间格式
pstmt.executeUpdate();
DBUtil.commit(conn);
} catch (SQLException e) {
DBUtil.rollback(conn);
e.printStackTrace();
} finally {
DBUtil.close(pstmt);
DBUtil.close(conn);
}
} /**
* 删除
* @param id
*/
public void delete(int id) {
Connection conn = DBUtil.getConn();
PreparedStatement pstmt = null;
String sql = " delete from t_student where id=?";
try {
pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id);
pstmt.executeUpdate();
DBUtil.commit(conn);
} catch (SQLException e) {
DBUtil.rollback(conn);
e.printStackTrace();
} finally {
DBUtil.close(pstmt);
DBUtil.close(conn);
}
} /**
* 批量删除
* @param ids
*/
public void deleteBatch(int[] ids) { Connection conn = DBUtil.getConn();
PreparedStatement pstmt = null;
String sql = " delete from t_student where id=?";
try {
pstmt = conn.prepareStatement(sql);
for (int id : ids) {
pstmt.setInt(1, id);
pstmt.addBatch();
}
pstmt.executeBatch();
DBUtil.commit(conn);
} catch (SQLException e) {
DBUtil.rollback(conn);
e.printStackTrace();
} finally {
DBUtil.close(pstmt);
DBUtil.close(conn);
}
} /**
* 修改
* @param student
*/
public void update(Student student) {
Connection conn = DBUtil.getConn();
PreparedStatement pstmt = null;
String sql = " update t_student set name=?,password=?,sex=?,age=?,birthday=?,memo=?,photo=?,reg_time=? where id=?";
try {
pstmt = conn.prepareStatement(sql); pstmt.setString(1, student.getName());
pstmt.setString(2, student.getPassword());
pstmt.setString(3, student.getSex());
pstmt.setInt(4, student.getAge());
pstmt.setDate(5, new java.sql.Date(student.getBirthday().getTime())); // 只存年月日这种形式
pstmt.setString(6, student.getMemo());
try {
// 构建一个输入流存blob
pstmt.setBlob(7, new FileInputStream(student.getPhoto()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
pstmt.setTimestamp(8, new java.sql.Timestamp(student.getRegTime().getTime())); // 完整的时间格式
pstmt.setInt(9, student.getId()); pstmt.executeUpdate();
DBUtil.commit(conn);
} catch (SQLException e) {
DBUtil.rollback(conn);
e.printStackTrace();
} finally {
DBUtil.close(pstmt);
DBUtil.close(conn);
}
} /**
* 查找
* @param id
* @return
*/
public Student find(int id) {
Connection conn = DBUtil.getConn();
PreparedStatement pstmt = null;
ResultSet resultSet = null;
String sql = " select * from t_student where id=?";
Student student = null;
try {
pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id);
resultSet = pstmt.executeQuery(); if (resultSet.next()) {
student = new Student();
student.setId(resultSet.getInt("id"));
student.setName(resultSet.getString("name"));
student.setAge(resultSet.getInt("age"));
student.setBirthday(resultSet.getDate("birthday"));
student.setMemo(resultSet.getString("memo"));
student.setPassword(resultSet.getString("password"));
student.setRegTime(resultSet.getTimestamp("reg_time"));
student.setSex(resultSet.getString("sex"));
InputStream in = resultSet.getBlob("photo").getBinaryStream();
String path = "d:\\ltf.jpg";
try {
OutputStream out = new FileOutputStream(path);
copy(in, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
student.setPhoto(path);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(resultSet);
DBUtil.close(pstmt);
DBUtil.close(conn);
}
return student;
} private void copy(InputStream in, OutputStream out) {
int i = 0;
try {
while ((i = in.read()) != -1) {
out.write(i);
}
out.flush();
} catch (IOException e) { e.printStackTrace();
}
} /**
* 查询多条记录
* @return
*/
public List<Student> query() {
Connection conn = DBUtil.getConn();
PreparedStatement pstmt = null;
ResultSet resultSet = null;
String sql = " select * from t_student ";
List<Student> studentList = new ArrayList<Student>(); try {
pstmt = conn.prepareStatement(sql); resultSet = pstmt.executeQuery(); while (resultSet.next()) {
Student student = new Student();
student.setId(resultSet.getInt("id"));
student.setName(resultSet.getString("name"));
student.setAge(resultSet.getInt("age"));
student.setBirthday(resultSet.getDate("birthday"));
student.setMemo(resultSet.getString("memo"));
student.setPassword(resultSet.getString("password"));
student.setRegTime(resultSet.getTimestamp("reg_time"));
student.setSex(resultSet.getString("sex"));
InputStream in = resultSet.getBlob("photo").getBinaryStream();
String path = "d:\\ltf.jpg";
try {
//将数据库存的图片放到磁盘的某个位置
OutputStream out = new FileOutputStream(path);
copy(in, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
student.setPhoto(path);
studentList.add(student);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.close(resultSet);
DBUtil.close(pstmt);
DBUtil.close(conn);
}
return studentList;
} }
测试类:DaoTest
package jdbc.test;
import static org.junit.Assert.fail; import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; import jdbc.bean.Student;
import jdbc.dao.StudentDao; import org.junit.Test; public class DaoTest { @Test
public void test() {
fail("Not yet implemented"); Student s=new Student();
//s.setId(3);
s.setName("zss");
s.setPassword("zss");
s.setSex("女");
s.setAge(21);
try {
s.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("1980-01-01"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
s.setMemo("我人还不错");
s.setPhoto("c:\\ltf.jpg");
s.setRegTime(new Date()); StudentDao sd=new StudentDao();
//sd.save(s);
//sd.update(s);
//sd.delete(1);
//sd.deleteBatch(new int[]{2,3});
System.out.println(sd.query().size());
} }
每次SQL操作都需要建立和关闭连接,这势必会消耗大量的资源开销,如何避免
分析:可以采用连接池,对连接进行统一维护,不必每次都建立和关闭。事实上这是很多对JDBC进行封装的工具所采用的。(等看到hibernate,spring连接数据库和事务的时候在研究一下。)
参考:
通过JDBC进行简单的增删改查(以MySQL为例) http://www.cnblogs.com/wuyuegb2312/p/3872607.html
JDBC学习之-如何获取Connection http://blog.csdn.net/luohuacanyue/article/details/8770450
java_jdbc_oracle简单总结(2016-11-23)的更多相关文章
- 最新的 cocoapods 安装与使用(2016.11)
cocoapods简介: cocoapods 是iOS的类库管理工具,可以让开发者很方便集成各种第三方库,而不用去网站上一个个下载,再一个个文件夹的拖进项目中,还得添加相关的系统依赖库.只需要安装好c ...
- 【读书笔记】2016.11.19 北航 《GDG 谷歌开发者大会》整理
2016.11.19 周六,我们在 北航参加了<GDG 谷歌开发者大会>,在web专场,聆听了谷歌公司的与会专家的技术分享. 中午免费的午餐,下午精美的下午茶,还有精湛的技术,都是我们队谷 ...
- U3D笔记11:47 2016/11/30-15:15 2016/12/19
11:47 2016/11/30Before you can load a level you have to add it to the list of levels used in the gam ...
- 微信iphone7、 ios10播放视频解决方案 2016.11.10
2016.11.10日更新以下方法 微信最新出同层播放规范 即使是官方的也无法解决所有android手机的问题. 另外iphone 5 .5s 某些手机始终会弹出播放,请继续采用 “以下是老的解决办法 ...
- 【转载】webstorm11(注册,激活,破解,码,一起支持正版,最新可用)(2016.11.16更新)
很多人都发现 http://idea.lanyus.com/ 不能激活了 很多帖子说的 http://15.idea.lanyus.com/ 之类都用不了了 最近封的厉害仅作测试 选择 License ...
- Beta周第14次Scrum会议(11/23)【王者荣耀交流协会】
一.小组信息 队名:王者荣耀交流协会 小组成员 队长:高远博 成员:王超,袁玥,任思佳,王磊,王玉玲,冉华 小组照片 二.开会信息 时间:2017/11/23 17:02~17:14,总计12min. ...
- 第35次Scrum会议(11/23)【欢迎来怼】
一.小组信息 队名:欢迎来怼小组成员队长:田继平成员:李圆圆,葛美义,王伟东,姜珊,邵朔,阚博文小组照片 二.开会信息 时间:2017/11/23 17:03~17:24,总计21min.地点:东北师 ...
- Murano Weekly Meeting 2016.08.23
Meeting time: 2016.August.23 1:00~2:00 Chairperson: Kirill Zaitsev, from Mirantis Meeting summary: ...
- github javascript相关项目star数排行榜(前30,截止2016.11.18):
github javascript相关项目star数排行榜(前30,截止2016.11.18): 前端开源框架 TOP 100 前端 TOP 100:::::https://www.awesomes. ...
- 2018.11.23 浪在ACM 集训队第六次测试赛
2018.11.23 浪在ACM 集训队第六次测试赛 整理人:刘文胜 div 2: A: Jam的计数法 参考博客:[1] 万众 B:数列 参考博客: [1] C:摆花 参考博客: [1] D:文化之 ...
随机推荐
- Java中static和final的区别
static是静态修饰关键字,可以修饰变量和程序块以及类方法: 当定义一个static的变量的时候jvm会将将其分配在内存堆上,所有程序对它的引用都会指向这一个地址而不会重新分配内存: 当修饰一个程序 ...
- 转载: pyExcelerator(Python操作Excel内库)API 文档
1.pyExcelerator 主要通过俩个Object操作Excel: Workbook 和Worksheet2.pyExcelerator 读取Excel文件 parase_xls(filenam ...
- Microsoft Visual Studio 2013如何设置查找头文件的路径
- Bash For Loop Examples
How do I use bash for loop to repeat certain task under Linux / UNIX operating system? How do I set ...
- uvaoj 10397 - Connect the Campus【最小生成树】
uvaoj 10397 - Connect the Campus Many new buildings are under construction on the campus of the Univ ...
- PTA - - 06-图1 列出连通集 (25分)
06-图1 列出连通集 (25分) 给定一个有NN个顶点和EE条边的无向图,请用DFS和BFS分别列出其所有的连通集.假设顶点从0到N-1N−1编号.进行搜索时,假设我们总是从编号最小的顶点出发, ...
- php 链接access数据库
php链接access数据库代码 <?php $odbc = "Driver={Microsoft Access Driver (*.mdb)};Dbq=".realpath ...
- try与finally返回结果执行先后详解
先看一段代码: @Test public void test1(){ System.out.println(testf1()); } int testf1() { int x = 1; try { r ...
- 用Android++在Visual Studio中用C/C++开发Android应用
博客搬到了fresky.github.io - Dawei XU,请各位看官挪步.最新的一篇是:用Android++在Visual Studio中用C/C++开发Android应用.
- CSharp - Comparison between IComparer and IComparable
/* Author: Jiangong SUN */ I've already written an article introducing the usage of comparer here. I ...