1. 程式人生 > >JDBC進階功能2

JDBC進階功能2

一,Prepare
package jdbc2;

import Util.jdbcUtil;
import org.junit.Test;

import javax.management.Query;
import java.sql.*;

/**
* Created by dllo on 17/6/2.
*/
public class jdbc1Prepare {
/*
* preparestatement
* 1,可以防止SQL 注入
* 2,採取預編譯的操作方式,將sql語句先交給資料庫編譯好
* 只需要等待執行就可以了;
* 當多個重複語句被執行時效率會比statement高,速度快
* */
@Test
public void t1() throws ClassNotFoundException, SQLException {
Class.forName(“com.mysql.jdbc.Driver”);
Connection conn = DriverManager.getConnection(
“jdbc:mysql://localhost:3306/jdbc”
,”root”
,”111111”
);
// 舊的寫法
Statement statement = conn.createStatement();
//今天
//問號就是一個佔位符
PreparedStatement pstm = conn.prepareStatement(“INSERT INTO stu VALUES (NULL ,?,?)”);
//第一個引數是?的位置
//與VALUES後面括號中是否有null無關 是否有具體值無關
//只看問號 從1開始數

    pstm.setString(1,"張三");
    pstm.setInt(2,40);

    pstm.executeUpdate();
}
         @Test
public void t2Update() throws SQLException {
    Connection conn = jdbcUtil.getconnection();

    String update = "update  stu set name=? where id =?;";
    //獲得預處理物件
    PreparedStatement pstmt = conn.prepareStatement(update);

    // 將引數傳到sql語句中
    //查詢id 為1 的資料
    //將該條資料的NAME 欄位改為劉振洲
    pstmt.setString(1,"liuzhenzhou");
    pstmt.setInt(2,2);

    //執行語句
    pstmt.executeUpdate();
}
@Test
public void t3Query() throws SQLException {
    Connection conn = jdbcUtil.getconnection();
    String Query = "SELECT * FROM stu WHERE name = ?;";
    PreparedStatement pstmt = conn.prepareStatement(Query);
    pstmt.setString(1,"zhangsan");


    ResultSet resultSet =pstmt.executeQuery();
    while (resultSet.next()){
        System.out.println();
    }
}

}
二,Batch
package jdbc2;

import Util.jdbcUtil;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
* Created by dllo on 17/6/2.
*/
public class jdbc2Batch {
public static void main(String[] args) throws SQLException {
Connection conn = jdbcUtil.getconnection();
PreparedStatement pstmt = conn.prepareStatement(“INSERT INTO stu VALUES (?,?,?)”);
pstmt.setInt(1,36);
pstmt.setString(2,”haha”);
pstmt.setInt(3,30);

    //通過這個方法可以實現批處理操作
    //呼叫這個方法後,會將這SQL先存起來,等待執行
    pstmt.addBatch();

    pstmt.setInt(1,21);
    pstmt.setString(2,"hengheng");
    pstmt.setInt(3,31);

    //又存了一條,等待執行
    pstmt.addBatch();
    //執行批處理中存著的SQL 語句
    // 批處理中各個SQL 語句之間執行成功或失敗是無聯絡的
    //即使第一條語句出現主鍵重複的錯誤
    //也不會影響第二條語句將資料插入到資料庫裡
    pstmt.executeBatch();
}

@Test
public void t1() throws SQLException {
    Connection conn = jdbcUtil.getconnection();
    PreparedStatement pstmt = conn.prepareStatement(
            "UPDATE stu SET  name = 'heihei'WHERE  name ='haha'");
    /*
    * 將上面的更新name為heihei的sql語句
    * 加入到批處理快取中
    * */
    pstmt.addBatch();
  //再新增一條刪除語句到批處理快取中
    pstmt.addBatch("DELETE  FROM  stu WHERE name = 'hengheng'");

    pstmt.executeBatch();


}

}
三,Transaction
package jdbc2;

import Util.jdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
* Created by dllo on 17/6/2.
*/
public class jsbc3Transaction {
public static void main(String[] args) throws SQLException {
Connection conn = jdbcUtil.getconnection();
//設定提交方式為手動提交
//開啟事務
try {
conn.setAutoCommit(false);
//建立一個預處理物件
PreparedStatement pstmt = conn.prepareStatement(
“UPDATE money SET m=? WHERE name = ?”);

        pstmt.setInt(1,900);
        pstmt.setString(2,"曹雲金");

        pstmt.executeUpdate();

         int a = 100/0;
        pstmt.setInt(1,1100);
        pstmt.setString(2,"郭德綱");

        pstmt.executeUpdate();

        conn.commit();
    } catch (Exception e) {
        try {
            conn.rollback();
            System.out.println("回滾了");
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

    }
}

}
四,DBUtils
import Util.jdbcUtil;
import jdbc2.Stu;
import jdk.internal.org.objectweb.asm.Handle;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.junit.Test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
* Created by dllo on 17/6/2.
*/
public class Jdbc4DBUtils {
/*
* DbUtils 是Apache 提供的一個
* 開源的方便我們操作jdbc的jar包
*
* QueryRunner類,是該jar包的核心類
* 所有的操作資料庫的方法都被封裝在這個類中
* 更新,查詢都是使用QueryRunner類
* */
@Test
public void ti() throws SQLException {
//獲得連線物件
Connection conn = jdbcUtil.getconnection();
//建立一個QueryRunner物件 用來執行sql語句
QueryRunner qr = new QueryRunner();

    String sql = "insert into stu values (null,'zyd',55)";
    //呼叫update方法可以執行增,刪,改等sql語句.
    qr.update(conn, sql);

    conn.close();
}

@Test
public void t2() throws SQLException {
    Connection conn = jdbcUtil.getconnection();
    QueryRunner qr = new QueryRunner();

    String queryOne = "select *from Stu where id = 11;";

    Stu query = qr.query(conn, queryOne, new BeanHandler<Stu>(Stu.class));

    System.out.println(query);
}

/*
 * 演示beanlisthandler 的使用
 * 使用beanlisthandler可以得到
 * 一個裝載指定型別物件的集合
 */

@Test
public void t3() throws SQLException {
    Connection conn = jdbcUtil.getconnection();
    QueryRunner qr = new QueryRunner();

    String queryall = "select * from stu;";
    List<Stu> query = qr.query(conn, queryall, new BeanListHandler<Stu>(Stu.class));

    //iter +tab
    for (Stu stu : query) {
        System.out.println(toString());
    }
}

@Test
public void t4() throws SQLException {
    Connection conn = jdbcUtil.getconnection();
    QueryRunner qr = new QueryRunner();

    String queryall = "select name,age from stu;";

    List<Map<String, Object>> query = qr.query(conn, queryall, new MapListHandler());
    System.out.println(query);
    //iter + tab
    for (Map<String, Object> stringObjectMap : query) {
        for (String s : stringObjectMap.keySet()) {
            System.out.println(query);
        }
    }

}

@Test
public void t5() throws SQLException {
    Connection conn = jdbcUtil.getconnection();
    QueryRunner qr = new QueryRunner();

    String sql = "select *from stu;";

    List<Object[]> query = qr.query(conn, sql, new ArrayListHandler());
    for (Object[] objects : query) {
        for (Object object : objects) {
            System.out.printf(object + "_");
        }
        System.out.println();
    }

    System.out.println(query);
}

/*
* resultsethandler 是介面
* beamhandler ,beanlisthandler等類都
* 實現了resultsethandler 是介面
*
* 介面回撥
* @
* */
@Test
public void t6() throws SQLException {
    Connection conn = jdbcUtil.getconnection();
    QueryRunner qr = new QueryRunner();
    String sql = "select *from stu where id = 1;";
    qr.query(conn, sql, new ResultSetHandler<Stu>() {
        @Override
        public Stu handle(ResultSet resultSet) throws SQLException {
            while (resultSet.next()) {
                Stu stu = new Stu();
                stu.setName(resultSet.getString(2));
                stu.setId(resultSet.getInt(1));
                stu.setAge(resultSet.getInt(3));
                return stu;
            }

            return null;
        }
    });

}

}