当前位置:网站首页>Use of JDBC
Use of JDBC
2022-06-28 05:52:00 【Yuanxiaobai】
Interfaces and procedures
Import jdbc Drive pack
Load database driver
Class.forName(“com.mysql.jdbc.Driver”); //mysql
Class.forName(" oracle.jdbc.driver.OracleDriver"); //oracle
Create database link objects
DriverManager class
effect :1) Manage and register drivers . 2) Create a connection to the database .
Methods in class :
DriverManager Static methods in a class | describe |
---|---|
Connection getConnection (String url, String user, String password) | By concatenating strings , user name , The password gets the data Library connection object |
Connection getConnection (String url, Properties info) | By concatenating strings , Property object to get the connection object |
database URL
Common databases URL How to write the address :
Oracle:jdbc:oracle:thin:@localhost:1521:orcl
SqlServer:jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=shen
MySql:jdbc:mysql://localhost:3306/shen
Connection
A connection to a specific database ( conversation ). Execute in the connection context SQL Statement and return the result .
Collection Is the most important object in database programming , All the interaction between the client and the database is through connection Object completed , The creation method is :
Connection conn = DriverManager.getConnection(url,user,pass);
Common methods of this object :
Method | describe |
---|---|
createStatement() | Create send to database sql Of statement object . |
prepareStatement(sql) | Create send precompile to database sql Of PrepareSatement object . |
prepareCall(sql) | Create the... That executes the stored procedure callableStatement object . |
setAutoCommit(boolean autoCommit) | Set whether transactions are automatically committed . |
commit() | Commit a transaction on a link . |
rollback() | Roll back transactions on this link . |
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String username = "scott";
String password = "tiger";
Connection conn = null;
//2. Get a link to the database
conn = DriverManager.getConnection(url, username, password);
establish statement object
Statement
For execution static SQL Statement and returns the object for which it generated the result .
All known sub interfaces : CallableStatement, PreparedStatement .
Jdbc In program Statement Object to send... To the database SQL sentence , The creation method is :
Statement stmt = conn.createStatement();
Statement Common methods of objects :
Method | meaning |
---|---|
executeQuery(String sql) | Used to send query statements to data . |
executeUpdate(String sql) | Used to send... To a database insert、update or delete sentence |
execute(String sql) | Used to send arbitrary... To the database sql sentence |
addBatch(String sql) | Put more than one sql Statement in a batch . |
executeBatch() | Send a batch of sql Statement execution . |
Statement stmt = null;
//3. Get to send... To the database sql Of the statement statement
stmt = conn.createStatement();
//4. Send... To the database sql
String sql = "select empno,ename,sal from emp";
stmt.executeQuery(sql);
PrepareStatement
Represents precompiled SQL Object of statement .
All known sub interfaces : CallableStatement
Its instance object can be called by :
PreperedStatement pstm = conn.preparedStatement()
PreperedStatement pstm = null;
String sql = "select * from users where name=? and password=?";
//3. Get to send... To the database sql Of the statement Preperedstatement
pstm = conn.preparedStatement(sql);// In this time , Precompile
pstm.setString(1, username);
pstm.setString(2, password);
//4. Send... To the database sql
pstm.executeQuery();// There's no need to pass in sql
Compare : be relative to Statement In terms of objects
- PreperedStatement You can avoid SQL Injection problem .
Such as :String sql=“select * from admin where loginname=’”+loginName+"+and loginpwd=’"+loginPwd+"’";
In the application :
-》 Please enter your account number : 333
-》 Please input a password : wer’or’1’='1
Actually sending :select * from admin where loginname=‘333’ and loginpwd=‘wer’or’1’=‘1’, Login successful ! - Statement Will cause the database to compile frequently SQL, May cause database buffer overflow .PreparedStatement But for SQL Precompile , So as to improve the efficiency of database execution .
- also PreperedStatement about sql Parameters in , Allow substitution in the form of placeholders , simplify sql Statement writing .
CallableStatement
Used to perform SQL The interface of the stored procedure .
Populate result set
Jdbc In program ResultSet Used to represent Sql Statement execution result .Resultset When encapsulating execution results , In a tabular way ,ResultSet Object maintains a cursor pointing to a table data row , In the beginning , The cursor is before the first line , call ResultSet.next() Method , You can make the cursor point to a specific row of data , Call the method to get the data of the row .
ResultSet
A data table that represents a database result set , Typically generated by executing statements that query the database .
1、 Get row
- ResultSet Provides a way to scroll the result set :
next(): Move to next line
Previous(): Move to previous line
absolute(int row): Move to specified row
beforeFirst(): Move resultSet Foremost .
afterLast() : Move to resultSet At the back of .
2、 Get value
- ResultSet Since it is used to encapsulate the execution result , So what this object provides is for getting data get Method :
Get any type of data
getObject(int index)
getObject(string columnName)
Get data of the specified type , for example :
getString(int index)
getString(String columnName)
ResultSet rs = null;
//4. Send... To the database sql, And get the resultset
String sql = "select empno,enamesal,birthday from emp";
rs = pstm.executeQuery(sql);
About ResultSet Note in interface :
- If the cursor is before the first line , Use rs.getXX() Get column values , Report errors :Before start of result set
- If the cursor is after the last line , Use rs.getXX() Get column values , Report errors :After end of result set
- Close the result set after use ResultSet, To shut down Statement, To shut down Connection
Traversal result set
//5. Take out the data of the result set
rs.afterLast();
rs.previous();
System.out.println("id=" + rs.getInt("empno"));
System.out.println("name=" + rs.getStringt("name"));
System.out.println("password=" + rs.getDouble("sal"));
System.out.println("birthday=" + rs.getObject("birthday"));
// Cycle out
while (rs.next()) {
System.out.println(rs.getInt("empno")+"\t"+rs.getString("ename")+"\t"+
rs.getDouble("sal"));
}
Close the connection
Jdbc After the program runs , Remember to release the program while it is running , The objects created to interact with the database , These objects are usually ResultSet, Statement and Connection object .
Be careful : To ensure that the resource release code can run , Resource release code must also be placed in finally In the sentence .
- Objects that need to be released :ResultSet Result set ,Statement sentence ,Connection Connect
- Release principle : Open first, then close , Turn off the last one .ResultSet Statement Connection
- In which code block :finally block
//7. Close links , Release resources
finally {
try {
if(rs!=null) {
rs.close();
rs =null;
}
if(stmt!=null) {
stmt.close();
stmt =null;
}
if(conn!=null) {
conn.close();
conn =null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
JDBC Configuration and use
// First step : First register the driver , Drivers are usually registered only once
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// The second step : Establishing a connection Connect, Set up url , user name , password
// url Format :JDBC: Sub protocol : Child name // Host name : port / Database name ? Property name = Property value &…
// Pay attention to is url There must be no extra space in the , Otherwise it will go wrong , useSSL=false To solve the problem of warnings during authentication
// String url = "jdbc:mysql://localhost:3306/test?" + "user=root&password=wsw011152&useUnicode=true&characterEncoding=UTF-8&useSSL=false";
String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
String name = "root";
String psw = "******";
Connection connect = null;
try {
connect = DriverManager.getConnection(url, name, psw);
// connect = DriverManager.getConnection(url);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// The third step : Create a Statement , It is generally recommended to use PreparedStatement
// 1、 Perform static SQL sentence . Usually by Statement Instance implementation .
// 2、 Execution dynamics SQL sentence . Usually by PreparedStatement Instance implementation .
// 3、 Execute database stored procedures . Usually by CallableStatement Instance implementation .
// String sql = "select * from user where id = ?";
String sql = "select * from user where id = ?";
try {
PreparedStatement ps = connect.prepareStatement(sql);
ps.setInt(1, 1); // Set parameters
// Step four : Execute statement , Get a result set , Process the results obtained
ResultSet result = ps.executeQuery();
while (result.next()){
System.out.println(result.getInt("id"));
System.out.println(result.getString("name"));
System.out.println(result.getInt("age"));
System.out.println(result.getString("salary"));
}
// Step five : close resource
result.close();
ps.close();
connect.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
边栏推荐
- Oracle 条件、循环语句
- Valueerror: iterative over raw text documents expected, string object received
- Object对象转 List集合
- ERP软件公司选型的重要根据
- Cryptography notes
- Interpretation of cloud native microservice technology trend
- 数据中台:数据治理的七把利剑
- Solution of dam safety automatic monitoring system for medium and small reservoirs
- How does guotaijun charge for safe varieties? Let's talk about the futures account opening process
- Drop down box for implementation
猜你喜欢
5G网络整体架构
Jenkins持续集成1
sklearn 特征工程(总结)
Codeworks 5 questions per day (1700 for each)
File foundation - read / write, storage
电子邮件营销的优势在哪里?为什么shopline独立站卖家如此重视?
YYGH-7-用户管理
Jdbc的使用
Valueerror: iterative over raw text documents expected, string object received
6. graduation design temperature and humidity monitoring system (esp8266 + DHT11 +oled real-time upload temperature and humidity data to the public network server and display the real-time temperature
随机推荐
V4L2 驱动层分析
数据中台:数据治理的七把利剑
Relevant implementation records of CSI and local disk
The length of pytorch dataloader the difference between epoch and iteration
Syn retransmission caused by IPVS
Prime mover × Cloud primordial is making sound, reducing cost and increasing efficiency lecture hall
bash install. SH ******** error
Zzuli:1072 frog climbing well
Install fmpefg
Typescript base type
Drop down box for implementation
Solution of dam safety automatic monitoring system for medium and small reservoirs
File foundation - read / write, storage
Introduction to uicollectionviewdiffabledatasource and nsdiffabledatasourcesnapshot
A full set of excellent SEO tutorials worth 300 yuan [159 lessons]
Cryptography notes
線條動畫
PS effect understanding record 2 color_ dodge color_ burn
全球国家(和地区)信息JSON数据
电商转化率这么抽象,到底是个啥?