1. How Java programs operate oracle
1. With odbc data source, use jdbc_odbc bridge connection to connect to the database
Note: odbc can only be connected locally, not remotely, that is, the java process and the Oracle database must be on the same machine.
Control Panel->Administrative Tools->Data Sources [ODBC], Add->Select Oracle in OraHome90->Finish
Data Source Name:test
TNS Service Name: Select Oracle's service
It is recommended to click Test Connection to pop up the pop-up box, enter the user name and password to test whether the connection is OK.
Java code:
package com.bijian.study; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class TestOra { public static void main(String[] args) { try { //1. Load the driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //2. Get the connection Connection ct = DriverManager.getConnection("jdbc:odbc:test","scott","tigger"); Statement sm = ct.createStatement(); ResultSet rs = sm.executeQuery("select * from emp"); while(rs.next()) { //print username System.out.println("Username: " + rs.getString(2)); } //Close the open resource rs.close(); sm.close(); ct.close(); }catch(Exception e) { e.printStackTrace (); } } }
2.jdbc connect to oracle
First, the oracle driver package needs to be added to the project.
package com.bijian.study; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class TestOra2 { public static void main(String[] args) { try { //1. Load the driver Class.forName("oracle.jdbc.driver.OracleDriver"); //2. Get the connection Connection ct = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:myora1","scott","tigger"); Statement sm = ct.createStatement(); ResultSet rs = sm.executeQuery("select * from emp"); while(rs.next()) { //print username System.out.println("Username: " + rs.getString(2)); } //Close the open resource rs.close(); sm.close(); ct.close(); }catch(Exception e) { e.printStackTrace (); } } }
3. Oracle paging case
Display user information of emp table in pagination
If the default port of Tomcat is occupied, open the apache-tomcat\conf\server.xml file and change port 8080 to another port.
The code looks like this:
<%@ page language="java" import="java.util.*,java.sql.*" contentType="text/html; charset=gbk" pageEncoding="gbk"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <h2>oracle paging case</h2> <table> <tr> <td>Username</td> <td>Salary</td> </tr> <% //1. Load the driver Class.forName("oracle.jdbc.driver.OracleDriver"); //2. Get the connection Connection ct = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:myora1","scott","tigger"); Statement sm = ct.createStatement(); int pageNow = 1; //Receive pageNow String s_pageNow = (String)request.getParameter("pageNow"); if(s_pageNow != null) { pageNow = Integer.parseInt(s_pageNow); } //Query the total number of pages int pageCount = 0; // total number of records int rowCount = 0; //Display several records per page int pageSize = 3; ResultSet rs = sm.executeQuery("select count(*) from emp"); if(rs.next()) { rowCount = rs.getInt(1); if(rowCount%pageSize==0) { pageCount = rowCount/pageSize; }else { pageCount = rowCount/pageSize + 1; } } rs = sm.executeQuery("select * from (select a1.*,rownum rn from (select * from emp) a1 where rownum<=" + pageNow*pageSize + ") where rn>=" + ((pageNow-1)* pageSize + 1)); while(rs.next()) { out.println("<tr>"); //print username out.println("<td>" + rs.getString(2) + "</td>"); out.println("<td>" + rs.getString(6) + "</td>"); out.println("</tr>"); } // print the total number of pages for(int i=1;i<=pageCount;i++) { out.print("<a href=MyTest.jsp?pageNow=" + i + ">[" + i + "] </a>"); } //Close the open resource rs.close(); sm.close(); ct.close(); %> </table> </body> </html>
2. How to manipulate data in oracle
1. Insert a date value with a specific format
Use the to_date function
insert into emp values(9998,'Xiaohong','MANAGER',7782,'11-November-1988',78.9,55.33,10); insert into emp values(9997,’小红2’,’MANAGER’,7782,to_date(’1988-12-12’,’yyyy-mm-dd’),78.9,55.33,10); insert into emp values(9996,’小红3’,’MANAGER’,7782,to_date(’1988/12/12’,’yyyy/mm/dd’),78.9,55.33,10);
2. Insert data using subquery
When using the values clause, only one row of data can be inserted at a time, and when using subqueries to insert data, a large amount of data can be inserted in one insert statement. When dealing with row migrations or loading data from external tables into the database, subqueries can be used to insert data.
create table kkk(myId nuber(4),myname varchar2(50),myDept number(5)); insert into kkk(myId,myname,myDept) select empno,ename,deptno from emp where deptno=10;
3. Update data using subquery
When using the update statement to update data, you can either use expressions or values to directly modify the data, or you can use subqueries to modify the data.
I hope that the position, salary and subsidies of employee Scott are the same as those of SMITH employees.
update emp set job=(select job from emp where ename=’SMITH’), sal=(select sal from emp where ename=’SMITH’), comm.=(select comm. from emp where ename=’SMITH’);
It should be written like this:
update emp set (job,sal,comm) = (select job,sal,comm. from emp where ename=’SMITH’) where ename=’SCOTT’;
3. Oracle transaction processing
1. A transaction is used to ensure data consistency. It consists of a group of related dml statements. All dml statements in this group either succeed or fail. For example, online transfers are typically processed with transactions to ensure data consistency.
2. When performing a transaction operation (dml statement), oracle will lock the affected table to prevent other users from changing the structure of the table.
3. When executing the use of the commit statement, the transaction can be committed. When the commit statement is executed, the changes of the transaction will be confirmed, the transaction will be ended, the savepoint will be deleted, and the lock will be released. When the commit statement is used to end the transaction, other sessions will be able to view the new data after the transaction has changed.
Set savepoint: savepoint a1; Delete operation: delete from emp where empno=9996; Then set the savepoint: savepoint a2; Accidental deletion operation: delete from emp where empno=9999; Rollback to a2: rollback to a2; Rollback to a1: rollback to a1;
4. Several important operations of the transaction
a. Set savepoint: savepint a;
b. Cancel part of the transaction: rollback to a;
c. Cancel all transactions: rollback
5. How to use transactions in java programs
ct.setAutoCommit(false);
ct.commit();
ct.rollback();
6. Read-only transactions
A read-only transaction refers to a transaction that only allows the execution of queries and does not allow any other dml operations. Using a read-only transaction can ensure that users can only obtain data at a certain point in time. Assuming that the air ticket agency starts to count today's sales at 18:00 every day, read-only transactions can be used at this time. After a read-only transaction is set, although other sessions may submit new transactions, the read-only transaction will not obtain the latest data changes, so that data information at a specific point in time can be guaranteed.
Set a read-only transaction: set transaction read only
Four. The use of sql functions
1. Character function
Character functions are the most commonly used functions in oracle.
lower(char): convert the string to lowercase format upper(char): Convert the string to uppercase format length(char): returns the length of the string substr(char,m,n): take a substring of a string replace(char1,search_string,replace_string) instr(char1,char2,[,n[,m]]): Get the position of the substring in the string
1) Display the names of all employees in lowercase
select lower(ename),sal from emp;
2) Display the names of all employees in uppercase
select upper(ename),sal from emp;
3) Display the name of the employee with exactly 5 characters
select * from emp where length(ename)=5;
4) Display the first three characters of all employee names
select substr(ename,1,3) from emp;
Description: substr (column name, from which digit, how many to take)
5) Display the names of all employees in capital letters
select upper(substr(ename,1,1)) || lower(substr(ename,2,length(ename)-1)) from emp;
6) Display the names of all employees in lowercase
select lower(substr(ename,1,1)) || lower(substr(ename,2,length(ename)-1)) from emp;
replace(char1,search_string,replace_string)
instr(char1,char2,[,n[,m]] take the position of the substring in the string
7) Display the names of all employees, replace all "A"s with a
select replace(ename,’A’,’a’) from emp;
2. Mathematical functions
The data types of input parameters and return values of mathematical functions are both numeric types. Mathematical functions include cos, cosh, exp, ln, log, sin, sinh, sqrt, tan, tanh, acos, asin, atan, round.
round(n,[m]): used to perform rounding. If m is omitted, it will be rounded to an integer; if m is a positive number, it will be rounded to m digits after the decimal point; if m is a negative number, it will be rounded to m digits of the decimal point. forward. trunc(n,[m]): used to truncate numbers. If m is omitted, the fractional part will be truncated. If m is positive, it will be truncated to m digits after the decimal point. If m is negative, it will be truncated to m before the decimal point. bit mod(m,n) floor(n): Returns the largest integer less than or equal to n ceil(n): Returns the smallest integer greater than or equal to n abs(n): returns the absolute value of the number n acos(n): Returns the arc cosine of a number asin(n): Returns the arcsine of a number atan(n): Returns the arc tangent of a number cos (n) exp(n): returns e raised to the nth power log(m,n): returns the logarithmic value power(m,n): returns m raised to the nth power
1) Display the daily salary of all employees in a 30-day month, ignoring the remainder
select trunc(sal/30),ename from emp; select floor(sal/30),ename from emp;
2) Examples
select round(sal) from emp where ename=’SMITH’; select round(comm,1),comm from emp where ename=’SMITH’; select trunc(comm,1),comm. from emp where ename=’SMITH’; select trunc(comm),trunk(comm,-1),comm. from emp where ename=’SMITH’; select floor(comm),comm from emp where ename=’SMITH’; select ceil(comm),comm from emp where ename=’SMITH’; select mod(10,2) from dual;--When doing oracle testing, you can use dual (dumb original table)
3)select abs(-13) from dual;
3. Date function
The date function is used to process data of date type. By default, the date format is dd-mon-yy, that is, 12-July-78
sysdate: return system time select sysdate from dual;
add_months(d,n)
last_day(d): Returns the last day of the month in which the specified date is located
1) Query employees who have been employed for more than 8 months
select * from emp where sysdate>add_months(hiredate,8);
2) Display the name and date of employment of the employee who has completed 10 years of service
select * from emp where sysdate>=add_months(hiredate,12*10);
3) For each employee, display the days of joining the company
select trunc(sysdate-hiredate) "Job days", ename from emp;
4) Find all employees who are employed on the 3rd last day of each month
select hiredate,ename from emp where last_day(hiredate)-2=hiredate;
4. Conversion function
The conversion function is used to convert the data type from one type to another. In this case, the data type of the value allowed by the oracle server is different from the actual one. At this time, the oracle server will implicitly convert the data type.
for example:
1)create table t1(id int);
insert into t1 values('10')--so Oracle will automatically convert '10' to 10
2)create table t2(id varchar2(10));
insert into t2 (id varchar2(10));--so oracle will automatically convert 1 to '1'
Although oracle can perform implicit data type conversion, it is not suitable for all situations. In order to improve the reliability of the program, we should use the conversion function to convert.
3)to_char
You can use select ename, hiredate, sal from emp where deptnoo=10; to display information, but, in some cases, this does not meet your needs.
a. Can the date display hours, minutes and seconds?
select ename,to_char(hiredate,’yyyy-mm-dd hh24:mi:ss’) from emp;
yy: two-digit year 2004->04 yyyy: Four-digit year 2004 mm: two-digit month August -> 08 dd: 2-digit day, 30th -> 30 hh24: 8 o'clock -> 20 hh12: 8 o'clock -> 08 mi, ss: display minutes, seconds
b. Can the salary be displayed in the specified currency symbol?
9: Display the number and ignore the leading 0 0: Display the number, if the number of digits is insufficient, it will be filled with 0 .: Display a decimal point at the specified position ,: Display a comma at the specified position $: add dollar before the number L: Add the local currency symbol before the number C: Add the international currency symbol before the number G: Display group separator at specified position D: Display a decimal point symbol (.) at the specified position
select ename,to_char(hiredate,’yyyy-mm-dd hh24:mi:ss’),to_char(sal,’L99999.99’) from emp; select ename,to_char(hiredate,’yyyy-mm-dd hh24:mi:ss’),to_char(sal,’L99,999.99’) from emp; select ename,to_char(hiredate,’yyyy-mm-dd hh24:mi:ss’),to_char(sal,$99,999.99’) from emp;
Show all employees hired in 1980
select * from emp where to_char(hiredate,’yyyy’)=1980;
Show all employees hired in December
select * from emp where to_char(hiredate,’mm’)=12;
5. System functions
sys_context
1) terminal: the identifier of the terminal corresponding to the current session client
2) language: language
3) db_name: current database name
4) nls_date_format: the date format corresponding to the current session client
5) session_user: the database user name corresponding to the current session client
6) current_schema: the default schema name corresponding to the current session client
7) host: returns the name of the host where the database is located
Through this function, you can query some important information, such as which database are you using?
select sys_context(‘userenv’,’db_name’) from dual; select sys_context(‘userenv’,’language’) from dual; select sys_context(‘userenv’,’session_user’) from dual; select sys_context(‘userenv’,’current_schema’) from dual;