当前位置:网站首页>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);
}
}
边栏推荐
- Using a* heuristic search to solve maze routing problem
- 智能指针、左值引用右值引用、lambda表达式
- Hcip-- review the homework for the next day
- Source code compilation!!
- Problems encountered in configuring Yum source
- On the dilemma faced by non transferable reputation points NFT SBTS
- web开发
- NLP learning roadmap (mind map) is very comprehensive and clear!
- 1. Pedestrian recognition based on incremental occlusion generation and confrontation suppression
- Markov random field: definition, properties, maximum a posteriori probability problem, energy minimization problem
猜你喜欢

Learning pyramid context encoder network for high quality image painting paper notes

【sklearn】tree.DecisionTreeClassifier

scikit-learn笔记

Hcip day 3 - mGRE experiment

Bear market bottoming Guide

1. Pedestrian recognition based on incremental occlusion generation and confrontation suppression

Mrs +apache Zeppelin makes data analysis more convenient

NLP learning roadmap (mind map) is very comprehensive and clear!

Using a* heuristic search to solve maze routing problem

How to avoid the most common mistakes when building a knowledge base?
随机推荐
Introduction to 51 single chip microcomputer (dedicated to the most understandable article for beginners)
Machine vision learning summary
OSS文件上传
Hcip day 3 - mGRE experiment
ZY: modify host name
Execution sequence of finally and return
MySQL深入了解
Recursive cascade network: medical image registration based on unsupervised learning
Support complex T4 file systems such as model group monitoring and real-time alarm. e
scikit-learn笔记
NumPy 统计相关函数示例教程
支撑复杂的模型群监控、实时告警等t4 文件系统。e
【sklearn】数据预处理
Learning pyramid context encoder network for high quality image painting paper notes
On the dilemma faced by non transferable reputation points NFT SBTS
C primer plus learning notes - 5. Pointer
C primer plus learning notes - 6. Arrays and pointers
ssm的整合
un7.23:如何在linix上安装MySQL?
编译型语言和解释型语言的区别