当前位置:网站首页>MySQL connection
MySQL connection
2022-07-24 05:20:00 【x0757】
1. Connect
JDBC---java database connection java Database connection . adopt java Code to manipulate records in database tables .
2. Additions and deletions --- These three patterns .
3. step :
(1) The load driver : Class.forName("com.mysql.cj.jdbc.Driver");
(2) Get the connection object : Connection conn=DriverManager.getConnection(url,u,p);
(3) Access to perform sql Object of statement : Statement st=conn.createStatement();
(4) Execute the addition, deletion and modification statement : st.executeUpdate(sql);
2.SQL Injection security issues
// demonstration sql Injected security issues
public static void main(String [] args) throws Exception{
Scanner scanner=new Scanner(System.in); //Scanner Class has it been mentioned .
System.out.print(" Please enter your account number :");
String username = scanner.nextLine();
System.out.print(" Please input a password :");
String password = scanner.nextLine(); // The account number and password you entered nextLine() You can enter a space Return to the end next() Entering a space is considered as the end of the input .
boolean b = sqlSafe(username, password);
}
// according to name Query data abc The demo queries database table records according to account and password If you can query, it means that the login is successful Otherwise, login fails
private static boolean sqlSafe(String name,String password) throws Exception{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai", "root", "PAssW0rd");
Statement statement = conn.createStatement();
// there admin Is it a dead data 123456 It is also a dead data
String sql="select * from user where username='"+name+"' and password='"+password+"'";
System.out.println(sql);
ResultSet rs = statement.executeQuery(sql);
while (rs.next()){
System.out.println(" Login successful ");
return true;
}
System.out.println(" Login failed ");
return false;
}You can find : Your account number can be entered at will Your password can also be entered at will however When entering the password or '4'='4 As long as this condition holds , Then you can login successfully . This is sql Injected security issues . Just do it according to the conditions sql. Then there will be sql Injection security issues .
How to solve sql Security injection problem :
1. Check the front end : -- Just guard against gentlemen Can't prevent villains .
2. The back end is also verified :-- Is it possible to verify every write function in the future ? The code becomes complicated .
3. perform sql Class Statement There is a problem , later stage PrepareStatement This class solves sql Injection security issues .
Statement and PrepareStatement difference ?
Statement There will be sql Injection security issues .Preparestatement There will be no sql Injection security issues .
Preparestatement yes Statement Subclasses of . Because of early use Statement Problems are found in this class , Later maintenance personnel create Statement To solve this problem . Be careful : Maintenance personnel will not perform maintenance on the original class
2.2 Use prepareStatement To solve sql Injection problem
// demonstration sql Injected security issues
public static void main(String [] args) throws Exception{
Scanner scanner=new Scanner(System.in); //Scanner Class has it been mentioned .
System.out.print(" Please enter your account number :");
String username = scanner.nextLine();
System.out.print(" Please input a password :");
String password = scanner.nextLine(); // The account number and password you entered nextLine() You can enter a space Return to the end next() Entering a space is considered as the end of the input .
boolean b = sqlSafe02(username, password);
}
private static boolean sqlSafe02(String name,String password) throws Exception{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai", "root", "pAssW0rd");
// Use PrepareStatement there ? It's a placeholder .
String sql="select * from user where username=? and password=?";
PreparedStatement ps = conn.prepareStatement(sql);// precompile sql
// Assign a value to the placeholder . Use different methods to assign values according to the type of placeholder
ps.setString(1,name); //1 Represents the first placeholder name: Represents the value of the first placeholder
ps.setString(2,password);
// perform sql sentence
ResultSet rs = ps.executeQuery();
while (rs.next()){
System.out.println(" Login successful ");
return true;
}
System.out.println(" Login failed ");
return false;
}3. Add, delete, modify and query the database
3.1 increase
@Test
public void test1()throws Exception{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn= DriverManager.getConnection
("jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai",
"root","pAssW0rd");
String sql="insert into student values(?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,2);
ps.setString(2," Xiaohao ");
ps.setInt(3,23);
ps.setString(4," Henan ");
ps.executeUpdate();
}3.2 Delete
@Test
public void test3()throws Exception{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn= DriverManager.getConnection
("jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai",
"root","pAssW0rd");
String sql="delete from student where id=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,12);
ps.executeUpdate();
}3.3 Change
@Test
public void test2()throws Exception{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn= DriverManager.getConnection
("jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai",
"root","pAssW0rd");
String sql="update student set name=? where id=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1," Li Si ");
ps.setInt(2,8);
ps.executeUpdate();
}3.4 check
@Test
public void test4()throws Exception{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn= DriverManager.getConnection
("jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai",
"root","pAssW0rd");
String sql="select * from student";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
int id= rs.getInt("id");
String name=rs.getString("name");
String address =rs.getString("address");
int age =rs.getInt("age");
System.out.println(id+"\t"+name+"\t"+address+"\t"+age);
}
}4. Take one dao Public parent of
4.1 Extract parent class
Because we have encapsulated an operation class for each table , Then there are many tables in the database , Then we will have many operation classes , These operation classes have some common code , In order to reduce code redundancy , We just extracted a parent class
private String driverName = "com.mysql.cj.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai";
private String user = "root";
private String password = "pAssW0rd";
protected PreparedStatement ps = null;
protected Connection conn = null;
protected ResultSet rs = null;
public Connection getConn()throws Exception{
Class.forName(driverName);
conn = DriverManager.getConnection(url,user,password);
return conn;
}
public void closeAll(){
try {
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public void edit(String sql,Object ... params){
try {
getConn();
ps = conn.prepareStatement(sql);
for(int i= 0;i<params.length;i++){
ps.setObject(i+1,params[i]);
}
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
closeAll();
}
}4.2 To add Delete Modify the method of extracting public
public Dept findOne(int id){
Dept d = new Dept();
try {
getConn();
String sql="select * from tb_emp where id=?";
ps =conn.prepareStatement(sql);
ps.setObject(1,id);
rs = ps.executeQuery();
while(rs.next()){
d.setId(rs.getInt("id"));
d.setName(rs.getString("name"));
d.setAge(rs.getInt("age"));
d.setJob(rs.getString("job"));
d.setSalary(rs.getInt("salary"));
d.setEntrydate(rs.getString("entrydate"));
d.setManagerid(rs.getInt("managerid"));
d.setDept_id(rs.getInt("dept_id"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll();
}
return d;
}
public List<Dept> findAll(){
List<Dept> list = new ArrayList<Dept>();
try {
getConn();
String sql="select * from tb_emp";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
Dept d = new Dept();
d.setId(rs.getInt("id"));
d.setName(rs.getString("name"));
d.setAge(rs.getInt("age"));
d.setJob(rs.getString("job"));
d.setSalary(rs.getInt("salary"));
d.setEntrydate(rs.getString("entrydate"));
d.setManagerid(rs.getInt("managerid"));
d.setDept_id(rs.getInt("dept_id"));
list.add(d);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll();
}
return list;
}
public void insertDpet(Dept dept){
String sql="insert into tb_emp values(null,?,?,?,?,?,?,?)";
edit(sql,dept.getName(),dept.getAge(),dept.getJob(),dept.getSalary(),
dept.getEntrydate(),dept.getManagerid(),dept.getDept_id());
}
public void updateDept(Dept dept){
String sql ="update tb_emp set name =? where id=?";
edit(sql,dept.getName(),dept.getId());
}
public void deleteDept(int id){
String sql = "delete from tb_emp where id=?";
edit(sql,id);
}4.3 test
public class Test1 {
DeptDao deptDao = new DeptDao();
@Test
public void testFindOne(){
Dept d = deptDao.findOne(1);
System.out.println(d.getId()+"\t"+d.getName()+"\t"+d.getAge()+"\t"+
d.getJob()+"\t"+d.getSalary()+"\t"+d.getEntrydate()+"\t"+
d.getManagerid()+"\t"+d.getDept_id());
}
@Test
public void testFindAll(){
List<Dept> all= deptDao.findAll();
for(Dept d:all){
System.out.println(d.getId()+"\t"+d.getName()+"\t"+d.getAge()+"\t"+
d.getJob()+"\t"+d.getSalary()+"\t"+d.getEntrydate()+"\t"+
d.getManagerid()+"\t"+d.getDept_id());
}
}
@Test
public void testInsert(){
Dept d = new Dept();
d.setName(" Xiao Yang ");
d.setAge(24);
d.setJob(" The manager ");
d.setSalary(20000);
d.setEntrydate("2022-05-07");
d.setManagerid(1);
d.setDept_id(2);
deptDao.insertDpet(d);
}
@Test
public void testUpdate(){
Dept d= new Dept();
d.setName(" liu ");
d.setId(16);
deptDao.updateDept(d);
}
@Test
public void testDelete(){
deptDao.deleteDept(16);
}
}
边栏推荐
- What are the core strengths of a knowledge base that supports customers quickly?
- [advanced mathematics] the difference between differentiable and differentiable functions
- Chapter5 foundation of deep learning
- 【sklearn】数据预处理
- 【NumPy】
- Token of space renewable energy
- 【Pytorch】nn.Module
- SSM整合
- The world's first large aerospace model came out. Wenxin's second supplement "Fuchun Mountain Residence map" is Baidu Pratt Whitney AI's perseverance
- C primer plus learning notes - 6. Arrays and pointers
猜你喜欢
![Embedded system transplantation [3] - uboot burning and use](/img/36/69daec5f1fe41bd3d0433d60816bba.png)
Embedded system transplantation [3] - uboot burning and use

Globally and locally consistent image completion paper notes

C primer plus learning notes - 6. Arrays and pointers

postgresql:在Docker中运行PostgreSQL + pgAdmin 4

Teach you how to weld CAD design board bottom (for beginners) graphic tutorial

How can NFT, whose stars enter the market against the market, get out of the independent market?
![[postgraduate entrance examination vocabulary training camp] day 10 - capital, expand, force, adapt, depand](/img/9a/a218c46806cf286f0518a72809e084.png)
[postgraduate entrance examination vocabulary training camp] day 10 - capital, expand, force, adapt, depand

Crazy God redis notes 09

熊市抄底指南

jdbc封装一个父类减少代码重复
随机推荐
un7.23:如何在linix上安装MySQL?
NLP learning roadmap (mind map) is very comprehensive and clear!
Heavy! The 2022 China open source development blue book was officially released
C primer plus learning notes - 6. Arrays and pointers
How to set up an internal wiki for your enterprise?
Binary SCA fingerprint extraction black Technology: go language Reverse Technology
Mrs +apache Zeppelin makes data analysis more convenient
1、基于增量式生成遮挡与对抗抑制的行人再识别
1. Input a 100 point score from the keyboard and output its grade according to the following principles: score ≥ 90, Grade A; 80 ≤ score < 90, grade B; 70 ≤ score < 80, grade C; 60 ≤ score < 70, grade
Tips for using the built-in variable vars in BeanShell
Smart pointer, lvalue reference, lvalue reference, lambda expression
Basic knowledge of MySQL database
智能指针、左值引用右值引用、lambda表达式
The difference between compiled language and interpreted language
Drools 开发决策表
Create and delete databases using databases
)的低字节来反馈给应用层或者成多种格式文档:
Emqx simple to use
Image painting for irregular holes using partial revolutions paper notes
【Pytorch】conv2d torchvision.transforms