首页 > 代码库 > JDBC操作总结
JDBC操作总结
1.将配置文件导入项目中
(1)oracle安装路径下搜索classes12(或其他)
(2)在项目中创建lib文件夹,将刚才拷贝的classes12拷贝到该目录下
(3)右键,add path进项目
写代码:
2.配置文件:
Class.forName("oracle.jdbc.driver.OracleDriver");
3.创建连接:
String url = "jdbc:oracle:thin:@localhost:1521:orcl"; conn = DriverManager.getConnection(url, "scott", "123");
4.取得申请:
sta = conn.createStatement(); set = sta.executeQuery("select * from emp");
5.操作数据:
(1)建立一个类与数据库结构相同
public class Emp { private int empno; private String ename; private String job; private int mgr; private Date hiredate; private double sal; private double comm; private int deptno; public Emp(){ }public int getEmpno() { return empno;}public void setEmpno(int empno) { this.empno = empno;}public String getEname() { return ename;}public void setEname(String ename) { this.ename = ename;}public String getJob() { return job;}public void setJob(String job) { this.job = job;}public int getMgr() { return mgr;}public void setMgr(int mgr) { this.mgr = mgr;}public Date getHiredate() { return hiredate;}public void setHiredate(Date hiredate) { this.hiredate = hiredate;}public double getSal() { return sal;}public void setSal(double sal) { this.sal = sal;}public double getComm() { return comm;}public void setComm(double comm) { this.comm = comm;}public int getDeptno() { return deptno;}public void setDeptno(int deptno) { this.deptno = deptno;}@Overridepublic String toString() { return "Emp [empno=" + empno + ", ename=" + ename + ", job=" + job + ", mgr=" + mgr + ", hiredate=" + hiredate + ", sal=" + sal + ", comm=" + comm + ", deptno=" + deptno + "]";} }
(2)建立一个Arraylist集合用以存储查询到的数据
List<Emp> emps = new ArrayList<Emp>(); while (set.next()) { Emp emp = new Emp(); emp.setEmpno(set.getInt("empno")); emp.setEname(set.getString("ename")); emp.setJob(set.getString("job")); emp.setMgr(set.getInt("mgr")); emp.setHiredate(set.getDate("hiredate")); emp.setSal(set.getDouble("sal")); emp.setComm(set.getDouble("comm")); emp.setDeptno(set.getInt("deptno")); emps.add(emp); }
(3)输出检验
for (Emp emp : emps) { System.out.println(emp.toString()); }
6.关闭资源:
finally { try { if (set != null) { set.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (sta != null) { sta.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
JDBC操作总结
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。