当前位置:网站首页>JDBC learning (I) -- implementing simple CRUD operations
JDBC learning (I) -- implementing simple CRUD operations
2022-06-28 06:09:00 【Mu Di%】
CRUD operation
Import database driver
stay src Create a directory named lib My bag , To hold jar file 
File——>Project Structure...——>Moudules
Check... In the document lib,ok Successful import 
Write a configuration file
# Database driven
driver=com.mysql.cj.jdbc.Driver
# stay / Add the local database name after
url=jdbc:mysql://localhost:3306/
# user name
username=root
# password
password=*******
Write a JDBCUtil Tool class
Easy to control the closing of the connection
- Connection class
- A link representing a database
- Some of the methods used
| Method | effect |
|---|---|
| createStatement() | Create send to database sql Of Statement object |
| prepareStatement(sql) | Create send precompile to database sql Of PrepareSatement object |
| repareCall(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 |
- Statement class
- Used to send... To a database SQL sentence
- Some of the methods used
| Method | effect |
|---|---|
| ecuteQuery(String sql) | Used to send... To data select sentence |
| 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 |
- PreparedStatement class
PreperedStatement yes Statement Subclasses of
- PreperedStatement You can avoid SQL Injection problem
- PreparedStatement But for SQL Precompile
- about sql Parameters in , Allow substitution in the form of placeholders , simplify sql sentence
- ResultSet class
- Used to represent Sql Statement execution result
- Some of the methods used
| Method | effect |
|---|---|
| getObject() | Get any type of data |
| getInt() | obtain int Data of type |
| getString() | obtain String Type data |
| 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 |
JDBCUtil Tool class
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcUtils {
private static final String url;
private static final String username;
private static final String password;
// static Blocks can be accessed without relying on any object
static {
try {
// Read db.properties Database connection information of file
JdbcUtils jdbcUtils = new JdbcUtils();
// Use reflection to get what the current object belongs to Class object , Get the right Class Class loader for objects , Read the file
InputStream in = jdbcUtils.getClass().getClassLoader().getResourceAsStream("db.properties");
Properties prop = new Properties();
prop.load(in);
// Get the database connection driver
String driver = prop.getProperty("driver");
// Get database connection URL Address
url = prop.getProperty("url");
// Get the database connection user name
username = prop.getProperty("username");
// Get the database connection password
password = prop.getProperty("password");
// Load database driver
//DriverManager.registerDriver(driver);
Class.forName(driver);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException {
// DriverManager Class loading driver , Create a link to the database
return DriverManager.getConnection(url, username, password);
}
// Release resources
public static void release(Connection conn, Statement st, ResultSet rs) {
if (rs != null) {
try {
// Turn off the ResultSet object
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (st != null) {
try {
// Closing is responsible for execution SQL Ordered Statement object
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
// close Connection Database connection object
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
CRUD operation
Add, delete, modify and query the database
- insert insert data
Connection conn=null;
PreparedStatement st = null;
try {
// Use the tool class you wrote before
conn = JdbcUtils.getConnection();
// The data to be inserted is replaced by placeholders
String sql = "insert into user(name,age,school,grade,gender,date) VALUES(?,?,?,?,?,now())";
// Send precompiled to the database sql sentence
st = conn.prepareStatement(sql);
// Use the index to set the inserted data value
st.setInt(2, age);
st.setString(1, name);
st.setString(3, school);
st.setString(4, grade);
st.setString(5, gender);
// call executeUpdate() The number of rows changed is returned , ad locum sql Statement to start execution
int num = st.executeUpdate();
if (num > 0) {
System.out.println(" Data added successfully ");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
JdbcUtils.release(conn, st, null);
}
— delete Delete data
Connection conn=null;
PreparedStatement st = null;
try {
// Use the tool class you wrote before
conn = JdbcUtils.getConnection();
// The number of rows of data to be deleted is replaced by placeholders
String sql = "delete from user where id="+id;
// Send precompiled to the database sql sentence
st = conn.prepareStatement(sql);
// call executeUpdate() The number of rows changed is returned , ad locum sql Statement to start execution
int num = st.executeUpdate();
if (num > 0) {
System.out.println(" Data deletion successful ");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
JdbcUtils.release(conn, st, null);
}
— update Update data
Connection conn=null;
PreparedStatement st = null;
try {
// Use the tool class you wrote before
conn = JdbcUtils.getConnection();
// The number of rows of data to be updated is replaced by placeholders
String sql = " update user set name=? where id="+id;
// Send precompiled to the database sql sentence
st = conn.prepareStatement(sql);
// Use the index to set the inserted data value
st.setString(1,name);
int num = st.executeUpdate();
// call executeUpdate() The number of rows changed is returned , ad locum sql Statement to start execution
if (num > 0) {
System.out.println(" Data updated successfully ");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
JdbcUtils.release(conn, st, null);
}
- select Query data
Connection conn=null;
PreparedStatement st = null;
ResultSet rs = null;
try {
// Use the tool class you wrote before
conn = JdbcUtils.getConnection();
String sql = " select * from user ";
// Send precompiled to the database sql sentence
st = conn.prepareStatement(sql);
// call executeQuery() Returns the result of the query ResultSet object
rs = st.executeQuery(sql);
// Take out the result of the query
while (rs.next()) {
System.out.print(rs.getString("name") + " ");
System.out.print(rs.getInt("age") + " ");
System.out.print(rs.getString("school") + " ");
System.out.print(rs.getString("grade") + " ");
System.out.print(rs.getString("gender") + " ");
System.out.println(rs.getString("date"));
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
JdbcUtils.release(conn, st, rs);
}
Write a class JDBC
CRUD How to operate
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class Jdbc {
// Data addition
public void insert() {
Scanner scanner = new Scanner(System.in);
// Table structure
//+--------+-------------+------+-----+---------+----------------
//| Field | Type | Null | Key | Default | Extra |
//| name | varchar(10) | NO | | NULL | |
//| age | tinyint | NO | | NULL | |
//| school | varchar(15) | YES | | NULL | |
//| grade | varchar(5) | YES | | NULL | |
//| gender | char(1) | NO | | NULL | |
//| id | int | NO | PRI | NULL | auto_increment |
//| date | varchar(20) | YES | | NULL | |
//+--------+-------------+------+-----+---------+----------------+
System.out.println("name");
String name = scanner.next();
System.out.println("school");
String school = scanner.next();
System.out.println("age");
int age = scanner.nextInt();
System.out.println("grade");
String grade = scanner.next();
System.out.println("gender");
String gender = scanner.next();
Connection conn=null;
PreparedStatement st = null;
try {
// Use the tool class you wrote before
conn = JdbcUtils.getConnection();
// The data to be inserted is replaced by placeholders
String sql = "insert into user(name,age,school,grade,gender,date) VALUES(?,?,?,?,?,now())";
// Send precompiled to the database sql sentence
st = conn.prepareStatement(sql);
// Use the index to set the inserted data value
st.setInt(2, age);
st.setString(1, name);
st.setString(3, school);
st.setString(4, grade);
st.setString(5, gender);
// call executeUpdate() The number of rows changed is returned , ad locum sql Statement to start execution
int num = st.executeUpdate();
if (num > 0) {
System.out.println(" Data added successfully ");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
JdbcUtils.release(conn, st, null);
}
}
// Delete data
public void delete() {
Scanner scanner = new Scanner(System.in);
System.out.println("id");
int id = scanner.nextInt();
Connection conn=null;
PreparedStatement st = null;
try {
// Use the tool class you wrote before
conn = JdbcUtils.getConnection();
// The number of rows of data to be deleted is replaced by placeholders
String sql = "delete from user where id="+id;
// Send precompiled to the database sql sentence
st = conn.prepareStatement(sql);
// call executeUpdate() The number of rows changed is returned , ad locum sql Statement to start execution
int num = st.executeUpdate();
if (num > 0) {
System.out.println(" Data deletion successful ");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
JdbcUtils.release(conn, st, null);
}
}
// Update data
public void update() {
Scanner scanner = new Scanner(System.in);
System.out.println("id");
Connection conn=null;
PreparedStatement st = null;
try {
// Use the tool class you wrote before
String name=scanner.next();
int id=scanner.nextInt();
conn = JdbcUtils.getConnection();
// The number of rows of data to be updated is replaced by placeholders
String sql = " update user set name=? where id="+id;
// Send precompiled to the database sql sentence
st = conn.prepareStatement(sql);
// Use the index to set the inserted data value
st.setString(1,name);
int num = st.executeUpdate();
// call executeUpdate() The number of rows changed is returned , ad locum sql Statement to start execution
if (num > 0) {
System.out.println(" Data updated successfully ");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
JdbcUtils.release(conn, st, null);
}
}
// Query data
public void select() {
Connection conn=null;
PreparedStatement st = null;
ResultSet rs = null;
try {
// Use the tool class you wrote before
conn = JdbcUtils.getConnection();
String sql = " select * from user ";
// Send precompiled to the database sql sentence
st = conn.prepareStatement(sql);
// call executeQuery() Returns the result of the query ResultSet object
rs = st.executeQuery(sql);
// Take out the result of the query
while (rs.next()) {
System.out.print(rs.getString("name") + " ");
System.out.print(rs.getInt("age") + " ");
System.out.print(rs.getString("school") + " ");
System.out.print(rs.getString("grade") + " ");
System.out.print(rs.getString("gender") + " ");
System.out.println(rs.getString("date"));
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
JdbcUtils.release(conn, st, rs);
}
}
}
Write a class JdbcTest Check for proper operation
- Writing test classes
import java.util.Scanner;
public class JDBCTest {
public static void main(String[] args) {
Jdbc test = new Jdbc();
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
switch (n) {
case 1:
test.insert();
break;
case 2:
test.update();
break;
case 3:
test.select();
break;
case 4:
test.delete();
break;
default:
System.out.println(" The data you entered is wrong !");
}
}
}
- The operation results are as follows
3
Xiao Ming 17 xx university Freshman male 2022-02-18 20:59:51
Xiaohong 18 xx university Freshman Woman 2022-02-18 21:00:17
Xiao Zhang 17 xx university Freshman male 2022-02-18 21:00:26
Xiao Li 17 xx university Freshman Woman 2022-02-18 21:00:35
Xiaoqing 17 xx university Freshman Woman 2022-02-18 21:00:49
Xiaofang 17 xx university Freshman male 2022-02-18 21:00:56
Xiao Song 17 xx university Freshman male 2022-02-18 21:01:03
Xiaoying 19 xx university Freshman Woman 2022-02-19 10:19:09
Xiao Hu 19 xx university Sophomore Woman 2022-02-19 12:14:26
Xiao He 17 xx university Freshman Woman 2022-02-21 16:19:42
Process finished with exit code 0
边栏推荐
- Object对象转 List集合
- Independent station sellers are using the five e-mail marketing skills, do you know?
- Taobao seo training video course [22 lectures]
- Common basic functions of Oracle
- Configure multiple database connections using the SSM framework
- 预训练模型参数不匹配
- ES9023音频解码芯片的工作原理
- pytorch详解
- Jenkins continues integration 2
- Oracle condition, circular statement
猜你喜欢
![Taobao seo training video course [22 lectures]](/img/81/21e844542b35010760d061abe905e9.jpg)
Taobao seo training video course [22 lectures]

Capacity scheduling absolute value configuration queue usage and pit avoidance

Drop down box for implementation

How the third-party libraries in cocoapod reference local header files

What is webrtc?

Openharmony gnawing paper growth plan -- json-rpc

lombok @EqualsAndHashCode 注解如何让对象.equals()方法只比较部分属性

Ethereum Classic的难度计算|猿创征文

【Paper Reading-3D Detection】Fully Convolutional One-Stage 3D Object Detection on LiDAR Range Images

Paper recommendation: efficientnetv2 - get smaller models and faster training speed through NAS, scaling and fused mbconv
随机推荐
Main functions of 5ggnb and ng ENB
Yygh-7-user management
Ethereum Classic的难度计算|猿创征文
Unity packaging webgl uses IIS to solve the error
death_ satan/hyperf-validate
Global country (and region) information JSON data
[staff] arpeggio mark
Object对象转 List集合
AutoCAD C# 多段线小锐角检测
Deep learning 19 loss functions
@Autowired注解为空的原因
使用pytorch和tensorflow计算分类模型的混淆矩阵
Scripting and programming languages
【Paper Reading-3D Detection】Fully Convolutional One-Stage 3D Object Detection on LiDAR Range Images
Difficulty calculation of Ethereum classic
pkg打包node工程(express)
easyui下拉框选中触发事件
EasyUI reset multi condition query
阿里云短信服务(完整指南),短信发送功能实现。
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance