Java 使用JDBC鏈接查詢操做數據

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.*;

public class JdbcTest {

    private static final Logger logger = LogManager.getLogger(JdbcTest.class);

    private Connection connection;

    /*
    鏈接數據庫
     */
    public void connectDatabase() {
        String driver = "驅動鏈接";
        String url = "數據庫鏈接";
        String userName = "用戶";
        String password = "密碼";
        logger.info("——開始鏈接數據庫——");
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, userName, password);
            logger.info("——數據庫鏈接成功——");
        } catch (Exception e) {
            logger.info("——數據庫鏈接出現異常——");
            logger.info(e);
        }
    }

    /*
    JDBC單個查詢操做
     */
    public void jdbcTest() throws Exception {
        String sql = "select id,name from student";
        PreparedStatement pstmt = connection.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            System.out.println("————————————");
            String id = rs.getString("id");
            System.out.println(id);
            String khzwmc = rs.getString("name");
            System.out.println(khzwmc);
        }
        rs.close();
        pstmt.close();
    }

    /*
    JDBC批量插入or更新or刪除操做
     */
    public void jdbcBatchTest() throws Exception {
        String[] names = {"Jack", "Tom", "Rose"};
        // 關閉自動提交
        connection.setAutoCommit(false);
        Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        for (int i = 0; i < names.length; i++) {
            String sql = "insert into student(id, name) values(" + (i + 1) + ", " + names[i] + ")";
            stmt.addBatch(sql);
        }
        // 批量操做
        stmt.executeBatch();
        // 手動提交
        connection.commit();
        stmt.clearBatch();
        stmt.close();
    }

    /*
    關閉鏈接
     */
    public void closeConnection() throws SQLException {
         if (null != connection) {
             connection.close();
         }
    }

    public static void main(String[] args) throws Exception {
        JdbcTest test = new JdbcTest();
        test.connectDatabase();
        test.jdbcBatchTest();
        test.jdbcTest();
        test.closeConnection();
    }
}
相關文章
相關標籤/搜索