文档详情

java中如何使用Oracle数据库.doc

发布:2017-06-07约3.36千字共4页下载文档
文本预览下载声明
Java与oracle数据库结合基础 Oracle数据库的使用 如要建一个用户名为stuMrg,密码为sa的用户,在这用户中建一个表Student(id,name,age) 其中id为自动增长序列 建表空间(用system用户登录)(建议平常练习,考试使用默认表空间即可,无需创建) create tablespace shcool_tablespace datafile D:\oracle\product\10.2.0\oradata\orcl\shcool.dbf size 10M 2)创建用户(用system用户登录) create user stuMrg identified by sa default tablespace shcool_tablespace//如果未新建表空间,则可省略,使用默认表空间 3)分配权限 grant connect,resource to stuMrg 4)建表(用stuMrg登录) 如果登录不进去,检查看下是否给用户分配权限 create table Student ( id number(11) primary key, name nvarchar2(20) not null, age number(2) not null, ) 5)创建自动增长列 create sequence stu_seq start with 1 increment by 1 nomaxvalue cache 10 6)插入一行数据 insert into student values(stu_seq.nextval,张三,17) 7)基本查询语法 a.查询所有数据 select * from Student b.按id查询,如查id=4的学生信息 select * from Student where id=4 c.姓名的模糊查询,如名字中带“张”的学生信息 select * from Student where name like ‘%张%’ java与Oracle数据库结合使用加载驱动类(注意:要在项目中添加Oracle的Jar驱动包) 1)加载驱动类 2)获取Connection对象(可提取至BaseDao中) 3)//创建PreparedStatement 示例:(向数据库添加 数据) public int save(Student student) { int i = 0; Connection conn = null; PreparedStatement st = null; // 使用?占位符:可读性和可维护性更高 String sql = insert into Student(id,name,age) values (stu_seq.nextval,?,?,?); try { // 加载驱动类 Class.forName(oracle.jdbc.driver.OracleDriver); // 获取Connection conn = DriverManager.getConnection( jdbc:oracle:thin:@localhost:1521:ORCL, stuMrg, sa); // 创建PreparedStatement、发送SQL(由数据库对SQL进行预编译:效率、性能更高) st = conn.prepareStatement(sql); // 给?占位符赋值 st.setInt(1, student.getId());// 索引从1开始 st.setString(2, student.getName()); st.setString(3, student.getAge); // 执行SQL i = st.executeUpdate();// 直接执行,不需要再传SQL } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { // 关闭对象,释放资源 try { if (st != null) st.close(); } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) conn.close(); } catch (SQLEx
显示全部
相似文档