三種執行SQL語句的的JAVA代碼


問題描述:

  連接數據庫,執行SQL語句是必不可少的,下面給出了三種執行不通SQL語句的方法。

1.簡單的Statement執行SQL語句。有SQL注入,一般不使用。

	public static void testStatement() throws Exception{
		Statement stm = null;
		ResultSet rs = null;
		DataBaseConn con = new DataBaseConn();
		try{
			stm = con.getMssqlConn().createStatement();
			rs = stm.executeQuery("select top 1 * from tfixitem");
			if(rs.next()){
				System.out.println("testStatement測試,FIXITEM_CODE = " + rs.getString("FIXITEM_CODE"));
			}
			con.closeCon();
		}catch(Exception e){
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	}

2.防止SQL注入的PreparedStatement執行SQL語句。

    public static void testPreparedStatement(){
        PreparedStatement pstm = null;
        ResultSet rs = null;
        DataBaseConn con = new DataBaseConn();
        try{
            pstm = con.getMssqlConn().prepareStatement("select * from tfixitem where fixitem_id = ?");
            pstm.setInt(1, 2);
            rs = pstm.executeQuery();
            if(rs.next()){
                System.out.println("testPreparedStatement測試,FIXITEM_CODE = " + rs.getString("FIXITEM_CODE"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

3.執行存儲過程的CallableStatement執行存儲過程SQL

    public static void testCallableStatement(){
        CallableStatement cstm = null;
        ResultSet rs = null;
        DataBaseConn con = new DataBaseConn();
        try{
            cstm = con.getMssqlConn().prepareCall("{call SP_QUERY_TFIXITEM(?,?,?,?,?,?,?,?)}");
            cstm.setInt(1, 2);
            cstm.setInt(2, 1);
            cstm.setInt(3, 0);
            cstm.setInt(4, 0);
            cstm.setString(5, "");
            cstm.setString(6, "");
            cstm.setString(7, "");
            cstm.setInt(8, 0);
            rs = cstm.executeQuery();
            if(rs.next()){
                System.out.println("testCallableStatement測試,FIXITEM_CODE = " + rs.getString("FIXITEM_CODE"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

總結:執行簡單SQL一般用preparedStatement,執行存儲過程使用CallableStatement


免責聲明!

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



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