【小白日記】Java學習 JDBC通過 junit單元測試編寫 CRUD 數據庫的增刪改查


CRUD : (create, read, update, delete)增刪該查


上一篇博文整理了關於sql 中 CRUD的語法
這次放到java工程當中來 進行執行
首先還是要依賴之前寫好的JDBCUtill 和jbdc.properties以及jdbc的jar文件
新建工程和配置環境和之前完全一樣不過多敘述

  • 建立class 命名為TestDemo
package com.sky.jdbc.test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import org.junit.Test;

import com.sky.jdbc.util.JDBCUtill;

/** * 使用后junit執行單元測試 * * @author WeiHaoLee * */
public class TestDemo {

	@Test
	public void testQuery() {
		// 查詢
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			// 獲取連接對象
			conn = JDBCUtill.getConn();
			// 根據連接對象,得到statement
			st = conn.createStatement();
			// 執行sql 語句返回resulset
			String sql = "select * from stu_list";
			rs = st.executeQuery(sql);

			// 遍歷結果集
			while (rs.next()) {
				String name = rs.getString("name");
				int age = rs.getInt("age");

				System.out.println(name + " " + age);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtill.release(conn, st, rs);
		}
	}
	
	
	
	@Test
	public void testInsert() {
		
		Connection conn = null;
		Statement st = null;
			try {
				// 獲取連接對象
				conn = JDBCUtill.getConn();
				// 根據連接對象,得到statement
				st = conn.createStatement();
				
				//執行添加
				String sql = "insert into stu_list values(null , 'aobama' , 59)";
				//此方法的返回結果代表改變的行數 改變行數大於0 則修改成功
				int result = st.executeUpdate(sql);
				
				if(result >0) {
					System.out.println("添加成功");
				}else {
					System.out.println("添加失敗");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				JDBCUtill.release(conn, st);
			}

	}

	@Test
	public void testDelete() {
		
		
		Connection conn = null;
		Statement st = null;
			try {
				// 獲取連接對象
				conn = JDBCUtill.getConn();
				// 根據連接對象,得到statement
				st = conn.createStatement();
				
				//執行添加
				String sql = "delete from stu_list where name= 'aobama'";
				//此方法的返回結果代表改變的行數 改變行數大於0 則修改成功
				int result = st.executeUpdate(sql);
				
				if(result >0) {
					System.out.println("刪除成功");
				}else {
					System.out.println("刪除失敗");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				JDBCUtill.release(conn, st);
			}
	}

	@Test
	public void testUpdate() {
		Connection conn = null;
		Statement st = null;
			try {
				// 獲取連接對象
				conn = JDBCUtill.getConn();
				// 根據連接對象,得到statement
				st = conn.createStatement();
				
				//執行添加
				String sql = "update stu_list set age = 28 where id = 5";
				//此方法的返回結果代表改變的行數 改變行數大於0 則修改成功
				int result = st.executeUpdate(sql);
				
				if(result >0) {
					System.out.println("更新成功");
				}else {
					System.out.println("更新失敗");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				JDBCUtill.release(conn, st);
			}
	}
}

由於引入了junit 所以直接到junit進行測試即可


免責聲明!

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



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