当前位置:网站首页>Introduction to JDBC (I) DML operation
Introduction to JDBC (I) DML operation
2022-06-23 05:23:00 【The silent Lord returns to the sand】
JDBC operation ( a key )
Review previous ways of connecting to the database
DOS Command mode , Graphically
shortcoming :
It can only be simply SQL Statement testing , Cannot manipulate database in projectExport through java Connect to the database in code mode —JDBC
summary :JDBC Is a set of standards for connecting to databases ; The specific implementation is provided by different databasesJDBC The core idea :

JDBC Operation steps :

Specific application :install 5.7 The database of , Driver package selection 5.X Driver package
Import driver package :- Create a new one under the project lib Folder , To hold jar file .
- take mysql drive mysql-connector-java-5.1.X Copy to project's lib In the folder .
- Choose lib Folder right-click Add as Libraay, Click on OK.
Common abnormal problems :
ClassNotFoundException Driver load failed
MySQLSyntaxErrorException: A database or SQL Statement exception
SQLException: Access denied Account or password error
MySQLIntegrityConstraintViolationException Primary key conflict
4.1 DML operation
// Case study : Add a piece of data to the position table
public class DMLTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. The load driver
Class.forName("com.mysql.jdbc.Driver");
//2. Get the connection object through the driver manager alt+enter Pop up exceptions and assignment variables
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb1", "root", "123");
//3. Get the execution object through the connection object
Statement st = conn.createStatement();
//4. Add, delete, modify and check Additions and deletions :executeUpdate
//String sql = "insert into t_jobs(job_id,job_title,min_salary,max_salary) values('QF_PRA','PRA',13000,18000)";
//String sql = "update t_jobs set min_salary=20000,max_salary=30000 where job_id='QF_PRA'";
String sql = "delete from t_jobs where job_id='QF_PRA'";
//5. Feedback results
int result = st.executeUpdate(sql);
System.out.println(" The number of items affected :"+result);
//6. close resource , Turn down the small one first and then turn it up
DBUtils.closeAll(st,conn);
}
}
4.2 DQL operation
class Student{
private int id;
private String name;
private int age;
//set/get And construction method
}
// Query the data of the student table
public class DQLTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///mydb1", "root", "123");
Statement st = conn.createStatement();
// Get the result set
ResultSet rs = st.executeQuery("select * from student");
List<Student> list = new ArrayList<>();
// Loop traversal , Get all the records ( Each cycle , Is a record
while(rs.next()){
//int id = rs.getInt(1); //1 On behalf of the 1 Column ; Application scenarios : Aggregate query feedback
int id = rs.getInt("id"); //id: The field name gets the value
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println(id+"-->"+name+"-->"+age);
// Application scenarios : Feedback on scattered content , Object encapsulation should be required ,
list.add(new Student(id,name,age));
}
System.out.println(" Data stored in the collection :"+list);
DBUtils.closeAll(rs,st,conn); // close resource
}
}
4.3 Secure login cases
- Create a user table User
- id , Primary key 、 Automatic growth .
- user name , String type , only 、 Non empty
- password , String type , Non empty
- Phone number , String type
- Insert 2 Test statements
To realize the login
- Enter the user name and password through the console user .
- The user name and password entered by the user are the conditions , Write a query SQL sentence .
- If the user exists , Prompt for successful login , Otherwise, the prompt fails .
public class LoginTest {
public static void main(String[] args) {
System.out.println(" Please enter a user name ");
Scanner sc = new Scanner(System.in);
String username = sc.nextLine(); // Get a line of content
System.out.println(" Please input a password ");
String password = sc.nextLine();
if(login2(username,password)){
// Login function
System.out.println(" Login successful ~!");
}else{
System.out.println(" Login failed ~!");
}
}
private static boolean login2(String username, String password) {
Connection conn = null;
PreparedStatement prst = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql:///mydb1", "root", "123");
//PreparedStatement: Preprocess the execution object ? As a placeholder
// benefits : 1. High safety , It's solved sql Injection problem
//2. The execution performance will be higher
//3. Convenient for batch processing
prst = conn.prepareStatement("select count(*) from user where username=? and password=?");
// Parameters 1: Corresponds to the first placeholder ? Subscript from 1 Start
prst.setString(1,username);
prst.setString(2,password);
// Get the result set
//sql Injection potential
rs = prst.executeQuery();
if(rs.next()){
int result = rs.getInt(1); // The aggregate function has only one field
return result>0; //result Not less than 0, Then return to true
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(rs,prst,conn);
}
return false;
}
private static boolean login(String username, String password) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql:///mydb1", "root", "123");
st = conn.createStatement();
// Get the result set
//sql Injection potential
String sql = "select count(*) from user where username='"+username+"' and password='"+password+"'";
rs = st.executeQuery(sql);
if(rs.next()){
int result = rs.getInt(1); // The aggregate function has only one field
return result>0; //result Not less than 0, Then return to true
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(rs,st,conn);
}
return false;
}
}
边栏推荐
- MCS:连续随机变量——LogNormal分布
- Three methods of GNSS velocity calculation
- 软件项目管理 8.4.软件项目质量计划
- 奇门遁甲辅助决策软件
- The tiobe programming language ranking is an indicator of the popular trend of programming languages
- Un processus GC complet pour le principe JVM
- Implementation of slider view
- LeetCode 797:所有可能的路径
- LeetCode-1757. 可回收且低脂的产品_SQL
- Mysql入门学习(三)之视图
猜你喜欢

MCS: continuous random variable - student's t distribution

Jetpack Compose 从开门到入门之 MenuBar桌面菜单(Desktop Menu)

Missing essential plugin

Jetpack compose menubar Desktop Menu from door opening to entry

Drag and drop frame

组合式API-composition-api

渗透测试基础 | 附带测试点、测试场景

Web 应用程序安全测试指南

Master shell, one article is enough!

APP自动化测试-Appium进阶
随机推荐
Master shell, one article is enough!
insert into... Where not exists insert to avoid repeated use
Drag and drop frame
Missing essential plugin
组合式API-composition-api
A compiler related bug in rtklib2.4.3 B34
Get bat command results in bat
九九乘法表.bat
Three tier architecture experiment
Zygote process
MySQL自定义序列数的实现
MCS: continuous random variable lognormal distribution
Go 分组 & 排序
【微服务|Nacos】Nacos版本相关问题一览
JVM原理之完整的一次GC流程
如何进行探索性数据分析
同步国内AOSP代码相关错误
VMware network connection error unit network service not found
konva 系列教程 1:konva 是什么?
Visual display of TEQC quality analysis results using teqcplot