当前位置:网站首页>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;
}
}
边栏推荐
- Rtklib new version 2.4.3 B34 test comparison
- [microservices | Nacos] Nacos realizes data isolation of multi environment and multi tenant
- STM32cube 串口使用DMA+IDLE接收不定长数据
- JDBC入门学习(二)之封装工具类
- 基金业绩评价
- 104. 简易聊天室7:使用 Socket 传递对象
- Snippet Manager snippetslab
- JDBC入门学习(四)之Druid连接池的使用
- ES6的Array.from方法创建长度为N的undefined数组
- The tiobe programming language ranking is an indicator of the popular trend of programming languages
猜你喜欢

Introduction and use of precise ephemeris

【微服务|Nacos】Nacos实现多环境和多租户的数据隔离

MCS:连续随机变量——Chi-Square分布

Introduction to unityshader -- rendering optimization technology in unity (IV)

What do Niu B programmers pay attention to when "creating an index"?

Arduino flame sensor (with code)

九九乘法表.bat

JVM原理之完整的一次GC流程

人脸识别 确定阈值

Three tier architecture experiment
随机推荐
The propeller framework v2.3 releases the highly reusable operator library Phi! Restructure development paradigm to reduce cost and increase efficiency
MCS: discrete random variable
MCS: continuous random variable - student's t distribution
Missing essential plugin
第九章 APP项目测试(1)
牛B程序员在“创建索引”时都会注意啥?
When SBAS encounters rtklib
Difficult to find a job in a bad environment? Ali on three sides. Fortunately, he has made full preparations and has offered
104. 简易聊天室7:使用 Socket 传递对象
Memory model of JVM principle
Penetration test basis | attached test points and test scenarios
618 how to break through the siege? Haier Zhijia: do a good job in digitalization of users
IDEA 代码开发完毕后,提交代码,提交后发现分支不对,怎么撤回
markdown给图片加背景色
小时候 觉得爸爸就是天 无所不能~
UnityShader入门精要——Unity中的渲染优化技术(四)
人脸识别 确定阈值
Missing essential plugin
JDBC入门学习(三)之事务回滚功能的实现
Economic development is driven by new technology