当前位置:网站首页>Oracle +JDBC
Oracle +JDBC
2022-07-27 20:27:00 【bigdata7】
JDBC
JDBC brief introduction
JDBC(Java Data Base Connectivity,java Database connection ) It's one for execution SQL Of the statement Java API, It can provide unified access for a variety of relational databases , It's used by a group Java Language written classes and interfaces .JDBC It provides a benchmark , From this, you can build more advanced tools and interfaces , Enable database developers to write database applications .
After we install the database , Our application can't use the database directly , Must pass the corresponding database driver , Dealing with database through driver . In fact, it is the database manufacturer's JDBC Interface implementation , to Connection Implementation class jar file .

JDBC + Oracle + Eclipse
brief introduction
We installed XE There is one in the version Oracle The official JDBC jar package , Location is :app\oracle\product\11.2.0\server\jdbc\lib
There are three
- ojdbc5: And jdk1.5 Corresponding
- ojdbc6: And jdk1.6 Corresponding
- ojdbc6_g:jdk1.6 Compiled version of
We can choose any one , file jdk yes 11 ,Oracle Yes, I have uploaded resources before 11g XE Version of
external JAR Package loaded into our project
In our Java Create a folder under the project Put these exteriors jar package The general file name is lib【 And src At the same level 】
Then right-click the project name , choice Build Path, Choose... As shown in the picture

choice labiries – 》 ModulePath — 》 Add JARS Select the... You created lib Below jar package —》 application OK to close

Then you can see lib There is a under the same level directory Referenced Libraries【 Application Library 】 This way jdbc Introduced into your library

Cognitive structure
This Jar Under the package are all classes related to databases , Interfaces, etc. . It and Java.sql as well as Javax.sql The three work together to operate the database , This JDBC It's just one. java Middleware for program operation database , It's also called JDBC drive
Java Program aid JDBC Connect to database
Java API
JDBC API Mainly located in JDK Medium java.sql In bag ( The expanded content is located in javax.sql In bag ), It mainly includes ( Italics represent interfaces , The driver provider is needed to implement ):
- DriverManager: Responsible for loading various drivers (Driver), And according to different requests , Return the corresponding database connection to the caller (Connection).
- Driver: The driver , Will load itself into DriverManager In the middle , And process the corresponding request and return the corresponding database connection (Connection).
- Connection: Database connection , Responsible for communication with database ,SQL Execution and transaction processing are all in a specific Connection In the environment . Can be generated to perform SQL Of Statement.
- Statement: To carry out SQL Query and update ( For static SQL Statement and single execution ).
- PreparedStatement: Used to execute... With dynamic parameters SQL Query and update ( Compile... On the server side , Allow repeat execution to improve efficiency ).
- CallableStatement: Used to call stored procedure .
- SQLException: Represents the establishment and closure of a database connection and SQL Exception occurred during statement execution ( It's a mistake ).
step
1. Load database driver
In programming, you should connect to the database , You must first load a specific vendor's database driver , Different databases have different loading methods . Such as :
load MySql drive :Class.forName(“com.mysql.jdbc.Driver”);
load Oracle drive :Class.forName(“oracle.jdbc.driver.OracleDriver”);
2. Create database connection :Connection Interface
This interface is used to create database connection
Connection conn = DriverManager.getConnection(String url,String username,String userpasswd);
- DriverManager Class
getConnection()Will return aConnectionDatabase connection object , Its parameters are not fixed , The most commonly used d These are the three - url: The address of the database service is usually written in a fixed way
- Oracle:
jdbc:oracle:thin:@ip Address : Port number (1521):XE - MySql:
jdbc:mysql://ip Address : Port number (3306)/ database【 As if 5.7 after 8.0 You need to write the time zone 】jdbc:mysql://localhost:3306/test?&useSSL=false&serverTimezone=UTC
- SqlServer:
jdbc:microsoft:sqlserver://ip Address : Port number ;DatabaseName = databasename
- Oracle:
- username: Connected database users
- userpasswd: Database user password
3. establish sql actuator :Statement Interface
Statement st = conn.createStatement();
4. perform sql
5. Process the returned result set or other operations
There are two common ways ,excuteQuery() and excuteUpdata() , The first return result set , It uses query sql sentence , The second is to increase 、 Delete 、 Change UPDATE statement of , Return integer data , Greater than 0 Then the execution is successful , Otherwise failure .
Generally, if it is a query, the result set is returned ResultSet, More on that later . There is one next() Method , The return value is Boolean type , Use it to get data .
6. Release database connection resources
When releasing the database connection, write in the order of first entering the stack and then exiting the stack , Then every time it is closed, there will be exceptions , And we have to make non empty judgments , Otherwise, it is easy to report null pointer abnormal errors .
give an example
package com.bigdata.jdbcdemo.oracle;
import java.sql.*;
public class demoSelect {
public static void main(String[] args) {
/** * The load driver * Create connection * establish Statement sql Perform object * perform sql * Processing return results * Release database resources */
// First of all It's good to close it at last
Connection conn = null;
Statement ste = null;
ResultSet rs = null;
try {
// Class cannot find exception
Class.forName("oracle.jdbc.OracleDriver");
// sql abnormal
conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:XE", "SCOTT", "lzyft1030");
ste = conn.createStatement();
String sql = "SELECT ENAME,JOB,SAL FROM EMP";
rs = ste.executeQuery(sql);
System.out.println(" full name \t Work \t Wages ");
while (rs.next()) {
System.out.println(rs.getString("ENAME")+"\t"+rs.getString("JOB")+"\t"+rs.getInt(3));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
// Do not do null Judge prevent NPE【NullPointerException】
try {
if (ste != null) {
ste.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Common interfaces
Connection Interface
Class.forName("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection(...);
Statement Interface
For execution static SQL Statement and returns the object for which it generated the result .
Three Statement class :
Statement:
from createStatement establish , For sending simple SQL sentence ( No parameters Sql, You can do it Sql Combine ).
Statement st = conn.createStatement();
String sql = "delete from tablename where id = "5" + "..." "; // No placeholders ? Can be combined So the security is not high String combination Change the string online or follow it with something else It breaks down directly
int code = st.excuteUpdate(sql);
ResultSet rst = st.excuteQuery(sql);
PreparedStatement :
Inherited from Statement Interface , from prepareStatement establish , Used to send messages containing one or more parameters 【 Place holder 】 Of SQL sentence .PreparedStatement Object ratio Statement Objects are more efficient , And it can prevent SQL Inject , So we usually use PreparedStatement.
【 Notice the difference between the interface and the creation method :PreparedStatement pst = conn.prepareStatement(sql);】
CallableStatement:
Inherited from PreparedStatement Interface , By way prepareCall establish , For calling stored procedures .
Commonly used Statement Method :
execute(String sql): Run statement , Returns whether there is a result setexecuteQuery(String sql): function select sentence , returnResultSetResult set .executeUpdate(String sql): functioninsert/update/deleteoperation , Returns the number of updated rows .addBatch(String sql): Put more than one sql Statement in a batch .executeBatch(): Send a batch of sql Statement execution .
ResultSet Interface
ResultSet Provides a way to retrieve different types of fields , Commonly used :
getString(int index)、getString(String columnName): Get in the database yes varchar、char Data objects of the same type .getFloat(int index)、getFloat(String columnName): Get in the database yes Float Type of data object .getDate(int index)、getDate(String columnName): Get in the database yes Date Data of type .getBoolean(int index)、getBoolean(String columnName): Get data of boolean type in the databasegetObject(int index)、getObject(String columnName): Get any type of data in the database .
ResultSet It also provides a way to scroll the result set :
next(): Move to next line , Returns a Boolean valueprevious(): Move to previous lineabsolute(int row): Move to specified rowbeforeFirst(): Move resultSet Foremost .afterLast(): Move to resultSet At the back of .
ResultSetMetaData
Metadata used to return the result set ,ResultSet Subclasses of , General method prototypes are ResultSet Of , When using, you can check API To use the
give an example
Tools for connecting and closing databases
package com.bigdata.jdbcdemo.oracle;
import java.sql.*;
public class DBConnection {
private static Connection conn = null;
/** * establish Oracle Database connection */
public static Connection getConnectOracle(){
try {
Class.forName("oracle.jdbc.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:XE","SCOTT","123");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
/** * Release resources */
public static void closeAll(ResultSet rst, PreparedStatement pst, Connection conn) {
try {
if (rst != null) {
rst.close();
}
if (pst != null) {
pst.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Specific exercises
package com.bigdata.jdbcdemo.oracle;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class PreparedStatementTest {
public static void main(String[] args) {
PreparedStatement pst = null;
ResultSet rst = null;
ResultSetMetaData rstmd = null;
Connection conn = DBConnection.getConnectOracle();
String sql = "select ename,job,sal from emp where deptno = ?";
try {
pst = conn.prepareStatement(sql);
pst.setInt(1, 10);
rst = pst.executeQuery();
while (rst.next()) {
System.out.println(rst.getString(1)+"\t"+rst.getString("JOB")+"\t"+rst.getInt(3));
}
rstmd = rst.getMetaData();
System.out.println(" Number of columns :"+rstmd.getColumnCount());
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBConnection.closeAll(rst, pst, conn);
}
}
}
Sql To Java Data type mapping
| SQL type | Java type |
|---|---|
| CHAR | java.lang.String |
| VARCHAR | java.lang.String |
| LONGVARCHAR | java.lang.String |
| NUMERIC | java.math.BigDecimal |
| DECIMAL | java.math.BigDecimal |
| BIT | boolean |
| TINYINT | byte |
| SMALLINT | short |
| INTEGER | int |
| BIGINT | long |
| REAL | float |
| FLOAT | double |
| DOUBLE | double |
| BINARY | byte[] |
| VARBINARY | byte[] |
| LONGVARBINARY | byte[] |
| DATE | java.sql.Date |
| TIME | java.sql.Time |
| TIMESTAMP | java.sql.Timestamp |
| BLOB | java.sql.Blob |
| CLOB | java.sql.Clob |
| Array | java.sql.Array |
| REF | java.sql.Ref |
| Struct | java.sql.Struct |
notes : This type matching is not a mandatory standard , specific JDBC Vendors may change this type of matching . for example Oracle Medium DATE The type is including hours, minutes and seconds , and java.sql.Date Only support mm / DD / yy .
Date transformation
java.sql.DateDate d = new Date(1900 + year, 1+month, day);- int Parameters of type
PreParedStatement()Medium sql Of Date type Not directly to_date() You need to use this Date Object to pass in
Oracle The type of Dateto_date( Date string ,' Format ');: By format String to dateto_char(date,' Format ');: Date to string in formatadd_month(date, Positive and negative numbers );: Add date monthlast_day(date);: The last item of the datedate + interval ‘ Positive and negative numbers ’ year/month( Number of digits , Default 2 position ): Press the following... For the date year or month Plus and minus numbers 【±】
Connect to the database with the configuration file
Create a file
create a file , It is best to put it under the same level directory of the class connected to the database , General file naming :date.properties , The format should be fixed
classDriver = oracle.jdbc.OracleDriver
url = jdbc:oracle:thin:@127.0.0.1:1521:XE
username = scott
userpasswd = 123
Create a class
java.util Below is a set of key value pairs ,Hashtable Subclasses of Preperties
use InputStream Object to read file data
InputStream is = The name of the class .class.getResourceAsStream("data.properties");
Prepareties p = new Prepareties();
p.load(is);
p.getProperty(key);// Get key value
Sample code
package com.bigdata.jdbcdemo.oracle;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class DBConnectByFile {
// Input stream reads configuration file Get resource flow with current class The parameter is the relative path of the configuration file
private static InputStream is = DBConnectByFile.class.getResourceAsStream("oracleConn.properties");
private static Properties properties = new Properties();
/** * @return Return drive */
public static String getDriverClass() {
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
return properties.getProperty("classDriver");
}
/** * @return return url */
public static String getUrl() {
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
return properties.getProperty("url");
}
/** * @return username */
public static String getUserName() {
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
return properties.getProperty("username");
}
/** * @return password */
public static String getPassword() {
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
return properties.getProperty("password");
}
public static Connection getConnection () {
Connection conn = null;
try {
Class.forName(getDriverClass());
conn = DriverManager.getConnection(getUrl(), getUserName(), getPassword());
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void closeAll(ResultSet rst, PreparedStatement pst, Connection conn) {
try {
if (rst != null) {
rst.close();
}
if (pst != null) {
pst.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// public static void main(String[] args) {
// Connection conn = getConnection();
// System.out.println(conn != null);
// }
}
rst.close();
}
if (pst != null) {
pst.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// public static void main(String[] args) {
// Connection conn = getConnection();
// System.out.println(conn != null);
// }
}
边栏推荐
- Redis thing learning
- 什么是多层感知机(什么是多层感知机)
- Preprocessing and macro definition
- Unified Modeling Language (UML) specification
- Huiding Technology: the acquisition of NXP vas business has been completed
- uva1421
- 为什么需要第三方支付?
- 传英特尔将停掉台积电16nm代工的Nervana芯片
- Libpcap library and pcap_ Sendpacket interface function understanding
- ES6--拓展运算符运用
猜你喜欢

C language -- array

To share the denoising methods and skills of redshift renderer, you must have a look

JS realizes video recording - Take cesium as an example

2022年,软件测试还能学吗?别学了,软件测试岗位饱和了...

预处理与宏定义

Wu Hequan: digital technology empowering "double carbon" practice according to local conditions

Codeworks 5 questions per day (average 1500) - day 24

数仓搭建——DWD层

Datepicker date selector in viewui compatible solution in ie11 browser

Office automation solution - docuware cloud is a complete solution to migrate applications and processes to the cloud
随机推荐
获得微店商品详情 API
LG集团宣布将向湖北捐赠300万元现金、120万个口罩、1万套防护服
Huawei's 150 member team rushed to the rescue, and Wuhan "Xiaotangshan" 5g base station was quickly opened!
JS jump to the page and refresh (jump to this page)
I'm also drunk. Eureka delayed registration and this pit
发布2年后涨价100美元,Meta Quest 2的逆生长
ES6 deleting attributes of objects_ ES6 delete an element "suggested collection" in the object
es6删除对象的属性_ES6删除对象中的某个元素「建议收藏」
十年测试老鸟聊聊移动端兼容性测试
GLTF模型添加关节控制
Following Huawei and MediaTek, the mobile phone chip manufacturer announced a donation of 7million yuan to Wuhan
速卖通:按关键字搜索商品 API
MediaTek releases Helio g80, a mid-range game phone chip
Can software testing be learned in 2022? Don't learn, software testing positions are saturated
华为150人团队驰援,武汉“小汤山”5G基站火速开通!
京东:获得商品详情原数据 API
PMP practice once a day | don't get lost in the exam -7.27 (including agility + multiple choices)
How to quickly improve the three minute response rate of Tiktok store? What will affect the reply rate of Tiktok store?
ES6 -- Deconstruction assignment
京东:按关键字搜索商品 API