通過Java代碼實現對數據庫的數據進行操作:增刪改查(JDBC)


在寫代碼之前,依然是引用mysql數據庫的jar包文件:右鍵項目—構建路徑—設置構建路徑—庫—添加外部JAR

在數據庫中我們已經建立好一個表xs ;分別有xuehao  xingming    xuexiao  三個列

然后我們開始碼代碼調用,進行增刪改查

首先是增加

import java.sql.*;


public class XueYuan {

    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");//加載驅動
        
        String jdbc="jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=GBK";
        Connection conn=DriverManager.getConnection(jdbc, "root", "");//鏈接到數據庫
        
        Statement state=conn.createStatement();   //容器
        String sql="insert into xs values('1108','張偉','漢企')";   //SQL語句
        state.executeUpdate(sql);         //將sql語句上傳至數據庫執行
        
        conn.close();//關閉通道

    }

執行后,數據中多了一行數據

刪除數據

import java.sql.*;


public class XueYuan {

    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");//加載驅動
        
        String jdbc="jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=GBK";
        Connection conn=DriverManager.getConnection(jdbc, "root", "");//鏈接到數據庫
        
        Statement state=conn.createStatement();   //容器
        String sql="delete from xs where xuehao='1108'";   //SQL語句
        state.executeUpdate(sql);         //將sql語句上傳至數據庫執行
        
        conn.close();//關閉通道

    }

}

執行后,數據庫中xuehao為“1108”的數據的整行被刪掉

修改數據

 

import java.sql.*;


public class XueYuan {

    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");//加載驅動
        
        String jdbc="jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=GBK";
        Connection conn=DriverManager.getConnection(jdbc, "root", "");//鏈接到數據庫
        
        Statement state=conn.createStatement();   //容器
        String sql="update xs set xuexiao='淄博漢企' where xuehao='1101' ";   //SQL語句
        state.executeUpdate(sql);         //將sql語句上傳至數據庫執行
        
        conn.close();//關閉通道

    }

}

 

數據庫中的1101對應的xuexiao發生了改變

 

 小結:數據的增刪改幾乎是一樣的唯一不同的是SQL語句不同而已

 

查詢數據

 查詢數據和增刪改不同的地方是,我們需要獲取,而正常獲取時,我們獲取到的是一個字符集

import java.sql.*;

import javax.xml.stream.events.StartElement;


public class Test3 {

    public static void main(String[] args) throws Exception {
        //導入驅動包
        Class.forName("com.mysql.jdbc.Driver"); 
        //鏈接至數據庫
        String jdbc="jdbc:mysql://127.0.0.1:3306/mydb";
    Connection conn=DriverManager.getConnection(jdbc, "root", "");
    
    Statement state=conn.createStatement();//容器
    String sql="select * from xs";           //sql語句
    ResultSet rs=state.executeQuery(sql);     //將sql語句傳至數據庫,返回的值為一個字符集用一個變量接收 
    
    while(rs.next()){    //next()獲取里面的內容
    System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
                         //getString(n)獲取第n列的內容
                            //數據庫中的列數是從1開始的
    }
    
    
    
    
    conn.close();
    }

獲取的結果

 

 

例子:

輸入賬號和密碼,在數據庫中獲取,如果有該信息,則顯示其登陸成功,如果沒有,則顯示輸入錯誤

有兩種方法可以實現:

import java.sql.*;
import java.util.*;

public class Login {

    public static void main(String[] args) throws Exception {
        // 輸入用戶名和密碼
        Scanner sc=new Scanner(System.in);
        System.out.println("請輸入賬號");
        String zh=sc.nextLine();
        System.out.println("請輸入密碼");
        String mm=sc.nextLine();
        
    //    zh=zh.replaceAll("\'", "\"");     //替換
    //    mm=mm.replaceAll("\'", "\"");        //替換
        
        //到數據庫驗證用戶名和密碼是否正確
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb", "root", "");
        Statement state=conn.createStatement();
        String sql="select * from yonghu where zhanghao='"+zh+"' and mima='"+mm+"'";
        ResultSet re=state.executeQuery(sql);
        
        //輸出:正確顯示歡迎,不正確顯示錯誤
        if(re.next()){
            System.out.println("登陸成功!"+re.getString(3)+" 歡迎你");
        }
        else{
            System.out.println("輸入賬號或密碼錯誤");
        }
        
        
        conn.close();
        
        

    }

}

實現了該功能

但是如果我們輸入

同樣會顯示登陸成功(sql注入攻擊),為避免出現這種情況我們加入兩個替換

zh=zh.replaceAll("\'", "\"")   將輸入的所有單引號全部換成雙引號,就可以避免這樣的漏洞;但是這種方法治標不治本,根本原因是字符串的拼接的原因

 



從根本上解決問題還有一種寫法 在SQL語句中,不確定的條件用?代替,PreparedStatement(sql) 容器來裝 setString( n ,m)來賦值n是第幾個問號的位置,m是賦的值(數據的增刪改同樣適用這種方法
 
import java.sql.*;
import java.util.*;

public class Login {
    public static void main(String[] args) throws Exception{
        //輸入用戶名和密碼
        Scanner sc=new Scanner(System.in);
        System.out.println("請輸入賬號");
        String zh=sc.nextLine();
        System.out.println("請輸入密碼");
        String mm=sc.nextLine();
        
        Class.forName("com.mysql.jdbc.Driver");
        String jdbc="jdbc:mysql://127.0.0.1:3306/mydb";
        Connection conn=DriverManager.getConnection(jdbc, "root", "");
        String sql="select * from yonghu where zhanghao=? and mima=?";      //sql語句
        PreparedStatement state=conn.prepareStatement(sql);                    //容器
        state.setString(1, zh);                                        //將第n個值替換成某個值
        state.setString(2, mm);
        ResultSet re=state.executeQuery();                       //上傳數據庫返回結果集
        
        if(re.next()){    //如果取到了值,那么輸出
            System.out.println("登陸成功"+re.getString(3)+",歡迎你");
        }
        else{
            System.out.println("登陸失敗,賬號或密碼輸入錯誤");
        }
        
        
    }
 
        

 

 

 
 
        

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM