1. 程式人生 > >第一天:java與mysql的連線工具類

第一天:java與mysql的連線工具類

                          第一天:java與mysql的連線工具類

java最新版馬上就要收費,這無疑是這門語言的衰敗起始,畢竟在中國收費便難發展,例如c#,但是畢業設計已經選好用java來寫一個動態網站,               

這已經是一個事實,還是得學,好在一法通萬法通,不至於一無所獲。

首先我們要把連線資料庫的工具類寫好,這裡面無非就那麼幾個固定的物件、語句,

第一步,我們需要導包,進入maven隨便選擇一個版本下載就是,網址是https://mvnrepository.com/artifact/mysql/mysql-connector-java

然後把jar包複製到java動態網站下的lib資料夾裡就是了,位置在/專案名/WebContent/WEB-INF/lib/mysql-connector-java-5.1.24-bin.jar

接下來就可以寫連線類了,來個最簡單的:

public class Jdbc {
    public static final String URL = "jdbc:mysql://localhost:3306/test";
    public static final String USER = "root";
    public static final String PWD = "123456";
    
    
public static void main(String[] args) { //update(); query(); } public static void update() { Connection conn = null; Statement stmt =null; PreparedStatement pstmt = null; ResultSet rs = null; try {
//載入驅動類 Class.forName("com.mysql.jdbc.Driver"); //與資料庫建立連線 conn = (Connection) DriverManager.getConnection(URL,USER,PWD); //執行sql //1.statement /*stmt = conn.createStatement(); String sql = "insert into user values(2,'qzj',123) "; int count = stmt.executeUpdate(sql);*/ //2.prepareStatement String sql = "insert into user values(?,?,?) "; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 3); pstmt.setString(2, "gg"); pstmt.setInt(3, 22); int count = pstmt.executeUpdate(); if(count > 0) { System.out.println("操作成功!"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } finally{ try { if(stmt != null) stmt.close(); if(conn != null) conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void query() { Connection conn = null; Statement stmt =null; PreparedStatement pstmt = null; ResultSet rs = null; try { //載入驅動類 Class.forName("com.mysql.jdbc.Driver"); //與資料庫建立連線 conn = (Connection) DriverManager.getConnection(URL,USER,PWD); //執行sql String sql = "select * from user"; /*stmt = conn.createStatement(); rs = stmt.executeQuery(sql);*/ pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while(rs.next()) { int id = rs.getInt("id"); String name = rs.getString("uname"); String pwd = rs.getString("upwd"); System.out.println(id+"--"+name+"--"+pwd); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } finally{ try { if(stmt != null) stmt.close(); if(conn != null) conn.close(); if(rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
View Code

基本上連線類中用到的就connection、statement、preparstatement、resultset四個物件,其中preparstatement是statement的子類,功能更多更好,

推薦優先使用preparstatement,理由如下:

1.編碼更加簡便(避免了字串的拼接)

String name = "zs" ;
int age = 23 ;

stmt:
String sql =" insert into student(stuno,stuname) values('"+name+"',  "+age+" )    " ;
stmt.executeUpdate(sql);

pstmt:
String sql =" insert into student(stuno,stuname) values(?,?) " ;
pstmt = connection.prepareStatement(sql);//預編譯SQL
pstmt.setString(1,name);
pstmt.setInt(2,age);

2.提高效能(因為 有預編譯操作,預編譯只需要執行一次)

需要重複增加100條數 
stmt:
String sql =" insert into student(stuno,stuname) values('"+name+"',  "+age+" )    " ;
for(100)
stmt.executeUpdate(sql);

pstmt:
String sql =" insert into student(stuno,stuname) values(?,?) " ;
pstmt = connection.prepareStatement(sql);//預編譯SQL
pstmt.setString(1,name);
pstmt.setInt(2,age);
for( 100){
pstmt.executeUpdate();
}

3.安全(可以有效防止sql注入),何為sql注入,就是--將客戶輸入的內容  和 開發人員的SQL語句 混為一體

stmt:存在被sql注入的風險  

(例如輸入  使用者名稱:任意值 ' or 1=1 --

  密碼:任意值)

分析:

當原始碼像select count(*) from login where uname='"+name+"' and upwd ='"+pwd+"' 

使用者有心搗亂就可以進行sql注入,輸入惡意使用者名稱就變成了以下後果:

select count(*) from login where uname='任意值 ' or 1=1 --' and upwd ='任意值'  ;//--是sql中的註釋,後面語句被註釋了

select count(*) from login where uname='任意值 ' or 1=1 ;//結果就變成了這樣,因為or1=1,最終就正確了

select count(*) from login ;

pstmt:有效防止sql注入,推薦使用pstmt

除了以上直接輸入連線資訊外還可以寫在一個/專案名/src/a.properties檔案,再從a.properties取出來用,程式碼如下:

private static String url = null;
    private static String user = null;
    private static String password = null;
    private static String dv = null;

    static {
        Properties prop = new Properties();
        InputStream in = JdbcUtils.class.getResourceAsStream("/a.properties");
        
        try {
            prop.load(in);
            url = prop.getProperty("url");
            user = prop.getProperty("user");
            password= prop.getProperty("password");
            dv = prop.getProperty("driver");
            
            //載入驅動類
            try {
                Class.forName(dv);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }                
    }

a.properties檔案語句如下:

url:jdbc:mysql://localhost:3306/diary?characterEncoding=utf8
user:root
password:123456
driver:com.mysql.jdbc.Driver

上面只是最簡單的也是最原始的連線工具類,再來個比較高階通用的:

package jdbc.util;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
//需要WebContent/WEB-INF/lib/mysql-connector-java-5.1.24-bin.jar
public class JdbcUtil {
    public static final String URL = "jdbc:mysql://localhost:3306/test";
    public static final String USER = "root";
    public static final String PWD = "123456";
    public static PreparedStatement pstmt = null ;
    public static Connection connection = null ;
    public static ResultSet rs = null ; 
    //通用增刪改
    public static boolean executeUpdate(String sql,Object[]params){
        try {
            pstmt = createPreParedStatement(sql,params);
            int count = pstmt.executeUpdate();
            if(count>0) {
                return true;
            }else {
                return false;
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } finally {
            closeAll(null,pstmt,connection);
        }        
    }
    //通用查
    public static ResultSet executeQuery(String sql,Object[]params)  {
        //Student student = null;        
        //List<Student> students = new ArrayList<>();    
        try {
            pstmt = createPreParedStatement(sql,params);
            rs = pstmt.executeQuery();
            return rs;
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }        
    }
    //匯入驅動,載入具體的驅動類
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection(URL,USER,PWD);        
    }
    public static PreparedStatement createPreParedStatement(String sql,Object[] params) throws ClassNotFoundException, SQLException {
        pstmt = getConnection().prepareStatement(sql);
        if(pstmt != null) {
            for(int i=0;i<params.length;i++) {
                //迴圈賦值,類似pstmt.setint(1,id)
                pstmt.setObject(i+1, params[i]);
            }
        }
        return pstmt;        
    }    
    public static void closeAll(ResultSet rs,Statement stmt,Connection connection)
    {
        try {
            if(rs!=null)rs.close();
            if(pstmt!=null)pstmt.close();
            if(connection!=null)connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }         
    }
    
    
    
    
}
View Code