1. 可以通过cmd 进入oracle控制台
如果是linux,需要先 # su - oracle 切换到oracle用户环境下
>> sqlplus /nolog //进入oralce控制台
>> conn sys/tiger as sysdba //以管理员权限登录
>> create user zmj identified by 123456; //创建用户名zmj密码123456
>> create tablespace ts_zmj datafile 'E:\oracleInstall\zmj_data.dbf' size 200M autoextend on; //创建一个表空间,大小200M,可以自动扩展
>> alter user zmj default tablespace ts_zmj; //将表空间ts_zmj给zmj用户使用
>> grant create session,create table,create view,create sequence,unlimited tablespace to zmj; //给用户分配权限
>> select *from session_privs; //查询当前用户所具有的权限
>> drop user zmj cascade; //删除用户及其相关对象
2. 导入dmp文件
imp chalco1129/chalco1129@127.0.0.1/orcl file=E:\oracleBakData\manual_chalco1129.dmp full=y
3. 导出dmp数据
3.1 导出某个用户下全部
exp chalco1230/chalco1230 file=/upload/manual_chalco1230.dmp
3.2 将数据库TEST完全导出,用户名system 密码manager 导出到D:\daochu.dmp中
exp system/manager@TEST file=d:\daochu.dmp full=y
3.3 将数据库中system用户与sys用户的表导出
exp system/manager@TEST file=d:\daochu.dmp owner=(system,sys)
3.4 将数据库中的表table1 、table2导出
exp system/manager@TEST file=d:\daochu.dmp tables=(table1,table2)
3.5 将数据库中的表table1中的字段filed1以"00"打头的数据导出
exp system/manager@TEST file=d:\daochu.dmp tables=(table1) query=\" where filed1 like '00%'\"
4. 创建表/序列
4.1 创建表 stu
create table stu (
id number(6) primary key,
name varchar2(20) not null,
gender number(1),
age number(3),
email varchar2(50) unique
);
4.2 创建序列 seq_stu 从1开始,每次增加1,无缓存
create sequence seq_stu start with 1 increment by 1 nocache;
4.3 插入表 stu ID根据序列自动增长,唯一性
insert into stu values (seq_stu.nextval,'张三',1,22,'abc@126.com');
5. 创建约束 / 索引 / 视图
5.1 创建sett_glsetting表的唯一约束,名称为un_abc;对应的表字段为abc
###创建唯一约束会自动创建一个同名的唯一索引####
alter table sett_glsetting add constraints un_abc UNIQUE (abc);
5.2 删除sett_glsetting表的唯一约束,名称为un_abc;对应的表字段为abc
###删除唯一约束会自动删除一个同名的唯一索引####
alter table sett_glsetting drop constraints un_abc;
5.3 可以单独创建索引 sett_glsetting表的索引,名称为idx_abc;对应的表字段为abc
create index idx_abc on sett_glsetting(abc);
5.4 索引是全局的,可以直接指定删除
drop index idx_glvoucheridrule;
5.5 创建/替换 视图
#####视图最好设置为只读
###1. 在多个人不同权限查看相同的一个或多个表需要显示不同内容时##
###2. 多个地方用到同样的查询结果,但是很复杂,那么单独做个视图,然后跟其他关联##
create or replace view view_sett_glsetting_for_hr as
(
select
id, --员工ID
officeid --办公ID
from sett_glsetting)
with read only;
6. 查询sql
6.1 decode 相当于if elseif elseif else
select name,decode(gender,1,'男',2,'女','妖')as gender from stu;
6.2 nvl 、nvl2 如果这个字段为空,则设置一个默认值;nvl2 如果不为空,则为第一个默认值,否则为第二个默认值
select name,nvl(EMAIL,'未填写邮箱')as email from stu;
select name,nvl2(email,'已设置邮箱','未设置邮箱') from stu;
6.3 to_date 字符串转成日期
select to_date('2020-01-01','yyyy-mm-dd') from dual;
6.4 rownum 当需取前几位的数据,如果其他字段用不上时;但rownum只能是<或=
select * from
(select stu.*,rownum as sturownum
from stu where rownum <= 10) a
where a.sturownum >= 2;
7. PLSQL过程化语言 Oracle自己的编程语言
7.1 plsql变量常量的使用
declare
--变量声明,包含静态赋值 / 动态赋值 / into指定
v_abc varchar2(20) := 'xiaoming';
v_bcd number(3) := &请输入年龄;
v_def varchar2(30);
--变量可以动态绑定某个表的字段
v_name stu.name%type;
--变量还可以动态绑定整个表的字段
v_stu stu%rowtype;
-- 常量声明
v_country constant varchar2(10) := 'China';
begin
--业务逻辑
dbms_output.put_line(v_abc || '----' || v_bcd);
select email into v_def from stu where id = 2;
dbms_output.put_line(v_def);
select name into v_name from stu where id = 2;
dbms_output.put_line(v_name);
select * into v_stu from stu where id = 2;
dbms_output.put_line(v_stu.name || '--' || v_stu.age || '--' || v_stu.email);
dbms_output.put_line(v_country);
exception
when NO_DATA_FOUND then
dbms_output.put_line('数据没有找到!');
end;
7.2 plsql中的流程控制
declare
v_stu stu%rowtype;
v_sql varchar2(100);
v_id stu.id%type := &请输入学生ID;
exception_age_invalid exception; --自定义异常
begin
v_sql := 'select * from stu where id=:id';
execute immediate v_sql
into v_stu
using v_id;
-- if else语句
if v_stu.age > 180 then
raise exception_age_invalid;
elsif v_stu.age > 60 then
dbms_output.put_line(v_stu.name || '--' || v_stu.age || ',该退休了!');
elsif v_stu.age > 18 then
dbms_output.put_line(v_stu.name || '--' || v_stu.age || ',可以工作!');
else
dbms_output.put_line(v_stu.name || '--' || v_stu.age || ',未成年!');
end if;
--case when 语句
case v_stu.gender
when 1 then
dbms_output.put_line(v_stu.name || '是男生!');
when 2 then
dbms_output.put_line(v_stu.name || '是女生!');
else
dbms_output.put_line(v_stu.name || '是男生!');
end case;
--异常处理 包括自定义异常和预定义异常
exception
when exception_age_invalid then
dbms_output.put_line('年龄无效!');
when NO_DATA_FOUND then
dbms_output.put_line('数据没有找到!');
end;
7.3 游标 cursor
declare
v_name stu.name%type := '&请输入学生姓名:';
v_stu stu%rowtype;
cursor cursor_query_all(stu_name varchar2) is select * from stu where name = stu_name;
begin
open cursor_query_all(v_name);
loop
fetch cursor_query_all into v_stu;
if cursor_query_all%found then
dbms_output.put_line(v_stu.name || ',年龄是' || v_stu.age);
else
exit;
end if;
end loop;
close cursor_query_all;
-- 如果是 for循环,会自动开启关闭游标,相对简单些
for v_stu in cursor_query_all(v_name) loop
dbms_output.put_line(v_stu.name || ',年龄是' || v_stu.age);
end loop;
end;
7.4 存储过程 procedure
7.4.1 创建一个存储过程
create or replace procedure pro_test111(
-- IN是输入参数 OUT是输出参数
p_name IN varchar2,
p_age IN number,
p_result IN OUT varchar2
) is
begin
dbms_output.put_line(p_name || p_age);
if 5 > 3 then
p_result := 'success';
end if;
end;
7.4.2 java程序调用存储过程
public void procedureTest(){
String sql = "{ call pro_test111(?,?,?)}";
CallableStatement call = null;
try {
call = conn.prepareCall(sql);
//IN需要set OUT需要reister
call.setString(1, "jdbc");
call.setInt(2, 2);
call.setString(3, "default");
call.registerOutParameter(3, Types.VARCHAR);
call.execute();
//拿到返回值
Object object = call.getObject(3);
System.out.println(object);
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭连接
DBConfig.close(call, conn);
}
}
8. 查询优化
8.1将数据量最小的表放到左侧,效率相对会高些;
9. Java代码调用
9.1 DBUtils工具调用
9.1.1 首先引入oracle6.jar commons-dbutils-1.4.jar c3p0-0.9.1.2.jar包
9.1.2 在新建db.properties
poolName=c3p0
className=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
username=chalco1129
password=chalco1129
initialPoolSize=10
minPoolSize=20
maxPoolSize=50
maxIdleTime=30
9.1.3 新建数据库连接配置信息工具类
package com.isoftstone.utils;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* 数据库连接配置信息
* @author mjzhud
*
*/
public class DBConfiguration {
private static Properties pro;
static {
//加载属性文件,读取数据库连接配置信息
pro = new Properties();
try {
pro.load(DBConfiguration.class.getResourceAsStream("/db.properties"));
} catch (IOException e) {
e.printStackTrace();
System.out.println("未找到配置文件!!!");
}
}
public static Connection getConnection() {
if ("c3p0".equals(pro.getProperty("poolName"))) return getC3P0Connection();
if ("dbcp".equals(pro.getProperty("poolName"))) return getC3P0Connection();
return null;
}
private static Connection getC3P0Connection(){
ComboPooledDataSource c3p0 = new ComboPooledDataSource();
try {
c3p0.setDriverClass(pro.getProperty("className"));
c3p0.setJdbcUrl(pro.getProperty("url"));
c3p0.setUser(pro.getProperty("username"));
c3p0.setPassword(pro.getProperty("password"));
c3p0.setInitialPoolSize(Integer.valueOf(pro.getProperty("initialPoolSize")));
c3p0.setMinPoolSize(Integer.valueOf(pro.getProperty("minPoolSize")));
c3p0.setMaxPoolSize(Integer.valueOf(pro.getProperty("maxPoolSize")));
c3p0.setMaxIdleTime(Integer.valueOf(pro.getProperty("maxIdleTime")));
return c3p0.getConnection();
} catch (PropertyVetoException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("连接失败,检查用户名和密码");
}
return null;
}
public static void close(Statement statement,Connection conn){
try {
if (statement != null) statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(ResultSet rs,Statement statement,Connection conn){
try {
if (rs != null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
close(statement,conn);
}
}
9.1.4 新建JdbcDBUtil工具类
package com.isoftstone.utils;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.junit.Before;
import org.junit.Test;
import bios.report.core.chart.t;
import com.isoftstone.manager.bean.Student;
import com.isoftstone.utils.DBConfiguration;
public class JdbcDBUtil {
private static Connection conn = DBConfiguration.getConnection();
public static QueryRunner runner = new QueryRunner();
public static int add(String sql) throws SQLException{
int count = -1;
try {
conn.setAutoCommit(false);
count = runner.update(conn , sql);
} catch (Exception e) {
conn.rollback();
} finally {
conn.commit();
}
if (count > 0) {
System.out.println("一条新增成功");
return 1;
}
System.out.println("一条新增失败");
return -1;
}
public static int add(String sql,Object[] params) throws SQLException{
int count = -1;
try {
conn.setAutoCommit(false);
count = runner.update(conn , sql, params);
} catch (Exception e) {
conn.rollback();
} finally {
conn.commit();
}
if (count > 0) {
System.out.println("一条新增成功");
return 1;
}
System.out.println("一条新增失败");
return -1;
}
public static int update(String sql) throws SQLException{
try {
conn.setAutoCommit(false);
runner.update(conn , sql);
} catch (Exception e) {
conn.rollback();
return -1;
} finally {
conn.commit();
}
System.out.println("一条更新成功");
return 1;
}
public static int update(String sql,Object[] params) throws SQLException{
try {
conn.setAutoCommit(false);
runner.update(conn , sql, params);
} catch (Exception e) {
conn.rollback();
return -1;
} finally {
conn.commit();
}
System.out.println("一条更新成功");
return 1;
}
public static int delete(String sql) throws SQLException{
try {
conn.setAutoCommit(false);
runner.update(conn , sql);
} catch (Exception e) {
conn.rollback();
return -1;
} finally {
conn.commit();
}
System.out.println("一条删除成功");
return 1;
}
public static int delete(String sql,Object[] params) throws SQLException{
try {
conn.setAutoCommit(false);
runner.update(conn , sql, params);
} catch (Exception e) {
conn.rollback();
return -1;
} finally {
conn.commit();
}
System.out.println("一条删除成功");
return 1;
}
/**
* DBUtils批处理,只能处理同一预处理sql语句
* @param sql
* @param paramArr
* @return
* @throws SQLException
*/
public static int dbUtilsBatch(String sql,Object[][] paramArr) throws SQLException{
int[] count = null;
try {
conn.setAutoCommit(false);
count = runner.batch(conn , sql, paramArr);
} catch (Exception e) {
conn.rollback();
return -1;
} finally {
conn.commit();
}
int updateCount = 0;
if (count != null && count.length > 0) {
for (int i : count) {
if (i > 0) updateCount++;
}
}
System.out.println("影响的行数="+updateCount);
return 1;
}
/**
* Statement可以批量处理各种sql
* @param sqls
* @return
* @throws SQLException
*/
public static int statementBatch(String[] sqls) throws SQLException{
Statement statement = conn.createStatement();
for (String sql : sqls) {
statement.addBatch(sql);
}
int[] count = null;
try {
conn.setAutoCommit(false);
count = statement.executeBatch();
} catch (Exception e) {
conn.rollback();
return -1;
} finally {
conn.commit();
DBConfiguration.close(statement, conn);
}
int updateCount = 0;
if (count != null && count.length > 0) {
for (int i : count) {
if (i > 0) updateCount++;
}
}
System.out.println("影响的行数="+updateCount);
return 1;
}
public static List<Map<String, Object>> queryList(String sql) throws SQLException{
return runner.query(conn, sql, new MapListHandler());
}
public static List<Map<String, Object>> queryList(String sql,Object[] params) throws SQLException{
return runner.query(conn, sql, new MapListHandler(),params);
}
}
9.1.5 新建Bean类
package com.isoftstone.manager.bean;
public class Student {
private long id;
private String name;
private int gender;
private int age;
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", gender=" + gender
+ ", age=" + age + ", email=" + email + "]";
}
}
9.1.6 新建Dao接口
package com.isoftstone.manager.dao;
import java.sql.SQLException;
import java.util.List;
import com.isoftstone.manager.bean.Student;
public interface StudentDao {
public int add(Student stu) throws SQLException;
public int updateById(Student stu) throws SQLException;
public int deleteById(int id) throws SQLException;
public Student queryById(int id) throws SQLException;
public List<Student> queryAll() throws SQLException;
}
9.1.7 新建Dao实现类
package com.isoftstone.manager.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.isoftstone.manager.bean.Student;
import com.isoftstone.manager.dao.StudentDao;
import com.isoftstone.utils.DBConfiguration;
import com.isoftstone.utils.JdbcDBUtil;
public class StudentDaoImpl implements StudentDao {
public int add(Student stu) throws SQLException {
String sql = "insert into stu values (seq_stu.nextval,?,?,?,?)";
Object[] params = new Object[]{stu.getName(),stu.getGender(),stu.getAge(),stu.getEmail()};
return JdbcDBUtil.add(sql,params);
}
public int updateById(Student stu) throws SQLException {
String sql = "update stu set name = ?,gender=?,age=?,email=? where id = ?";
Object[] params = new Object[]{stu.getName(),stu.getGender(),stu.getAge(),stu.getEmail(),stu.getId()};
return JdbcDBUtil.update(sql,params);
}
public int deleteById(int id) throws SQLException {
String sql = "delete from stu where id = " + id;
return JdbcDBUtil.delete(sql);
}
public Student queryById(int id) throws SQLException {
String sql = "select * from stu where id = ?";
return JdbcDBUtil.runner.query(DBConfiguration.getConnection(), sql, new BeanHandler<Student>(Student.class),id);
}
public List<Student> queryAll() throws SQLException {
String sql = "select * from stu where id = ?";
return JdbcDBUtil.runner.query(DBConfiguration.getConnection(), sql, new BeanListHandler<Student>(Student.class));
}
}
来源:CSDN
作者:朱梦君
链接:https://blog.csdn.net/qq_30426943/article/details/104063318