javaWeb實戰教程4-jdbc連線資料庫和junit單元測試
javaWeb實戰教程
2.5 junit單元測試
我們在平時做程式碼時,每完成一個方法都需要先測試再提交,在java中比較常用的一個測試方法就是使用junit。
首先在專案中加入junit的jar包:junit-4.7.jar
;將jar包複製到WEB-INF/lib目錄下。
新建一個包專門存放測試類:cn.funsoftware.Lesson.test
,再新建一個類:Lesson6JunitTest
。
我們可以寫一個公有方法,並在方法前加上註釋@Test來把這個方法變成一個測試方法,如:
@Test public void test1(){ System.out.println("測試方法1執行啦"); } @Test public void test2(){ System.out.println("測試方法2執行啦"); }
在方法上右擊run as-junit test。
junit還提供了@Before
、@After
兩個註解,使在執行測試方法前,會先執行@Before標記的方法,執行完測試方法後會執行@After標記的方法,且同時執行多個測試方法時,@Before
和@After
都會隨每個方法執行多次。
@Before public void before(){ System.out.println("@Before"); } @Test public void test1(){ System.out.println("測試方法1執行啦"); } @Test public void test2(){ System.out.println("測試方法2執行啦"); } @After public void after(){ System.out.println("@After"); }
junit還提供了@BeforeClass
、@AfterClass
兩個註解,被註解標記的方法必須是靜態static的,這兩個方法分別會在所有測試方法執行前執行和所有方法執行完成後執行:
@BeforeClass public static void beforeClass(){ System.out.println("@BeforeClass"); } @Before public void before(){ System.out.println("@Before"); } @Test public void test1(){ System.out.println("測試方法1執行啦"); } @Test public void test2(){ System.out.println("測試方法2執行啦"); } @After public void after(){ System.out.println("@After"); } @AfterClass public static void afterClass(){ System.out.println("@AfterClass"); }
在類上右擊Run As-junit test
,得到結果:
@BeforeClass
@Before
測試方法1執行啦
@After
@Before
測試方法2執行啦
@After
@AfterClass
通過結果我們能看出@AfterClass
和@After
、@BeforeClass
和@Before
的區別。
2.6 jdbc連線資料庫
在java中,連線資料庫通常是jdbc元件,我們先把jdbc的jar包加入到專案中:mysql-connector-java-5.1.42-bin.jar
。
使用jdbc連線資料庫通常情況下分為以下幾個步驟:
- 載入jdbc驅動:
Class.forName("com.mysql.jdbc.Driver");
- 開啟連結:
DriverManager.getConnection(資料庫地址,使用者名稱,密碼);
- 執行查詢:
PreparedStatement;
- 展開結果集:
ResultSet;
- 關閉連線:
close;
先在資料庫裡新建一張表:
CREATE TABLE `type` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`type` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4;
再在專案中新建一個javaBean來存資料,新建包cn.funsoftware.Lesson.bean,新建類Type.java:
package cn.funsoftware.Lesson.bean;
public class Type {
private int id;
private String name;
private int type;
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public int getType() {return type;}
public void setType(int type) {this.type = type;}
}
我們習慣把操作資料庫的內容都寫到一個叫做XXXDao的類裡,新建一個TypeDao.java:
package cn.funsoftware.Lesson.dao;
import cn.funsoftware.Lesson.bean.Type;
public class TypeDao {
public int add(String name,int type){
}
public void del(int id){
}
public void update(int id,String name,int type){
}
public Type getById(int id){
}
}
使用jdbc插入資料:
public int add(String name,int type){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=true",
"root","000000");
preparedStatement = connection.prepareStatement
("insert into type (name,type)values(?,?)",
Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, name);
preparedStatement.setInt(2, type);
preparedStatement.execute();
resultSet = preparedStatement.getGeneratedKeys();
if (resultSet.next()) {
System.out.println("插入資料id是" + resultSet.getInt(1));
return resultSet.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resultSet != null)
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (preparedStatement != null)
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (connection != null)
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return 0;
}
我們要保證無論資料庫操作是否成功,ResultSet、PreparedStatement、Connection都必須得到關閉,所以在程式程式碼外巢狀:
try {
//程式碼塊
}catch (Exception e) {
e.printStackTrace();
} finally {
if (resultSet != null)
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (preparedStatement != null)
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (connection != null)
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
刪除操作:
preparedStatement = connection.prepareStatement("delete from type where id=?");
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
更新操作:
preparedStatement = connection.prepareStatement("update type set name=?,type=? where id=?");
preparedStatement.setString(1, name);
preparedStatement.setInt(2, type);
preparedStatement.setInt(3, id);
preparedStatement.executeUpdate();
查詢操作:
preparedStatement = connection.prepareStatement("select * from type where id=?");
preparedStatement.setInt(1, id);
resultSet =preparedStatement.executeQuery();
if (resultSet.next()) {
Type type=new Type();
type.setId(resultSet.getInt("id"));
type.setName(resultSet.getString("name"));
type.setType(resultSet.getInt("type"));
return type;
}
我們來寫一個Lesson7Jdbc.java測試一下TypeDao:
public class Lesson7Jdbc {
@Test
public void test() {
TypeDao typeDao=new TypeDao();
// typeDao.add("測試1", 1);
// typeDao.del(6);
// typeDao.update(7, "測試2", 2);
Type type=typeDao.getById(7);
System.out.println(type.getName());
}
}
我們現在寫好了一個TypeDao.java來操作資料庫,但檢視程式碼發現大量的重複程式碼;java講究封裝,如果重複程式碼很多,代表程式優化不足,我們可以將部分程式碼封裝,來簡化TypeDao.java,也讓我們操作資料庫更方便。
dao內每個方法都有:
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=true", "root",
"000000");
我們可以把載入驅動和開啟connection寫成一個工具類,在cn.funsoftware.Lesson.utils內新建類DBUtil.java,將兩行程式碼寫進去:
public class DBUtil {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getcConnection() {
try {
return DriverManager.getConnection(
"jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=true", "root",
"000000");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
其中static{//程式碼}
叫靜態程式碼塊,JVM載入類時會執行靜態程式碼塊。
這樣我們優化下TypeDao.java裡的程式碼:
public int add(String name,int type){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = DBUtil.getcConnection();
preparedStatement = connection.prepareStatement("insert into type (name,type)values(?,?)",
Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, name);
preparedStatement.setInt(2, type);
preparedStatement.execute();
resultSet = preparedStatement.getGeneratedKeys();
if (resultSet.next()) {
System.out.println("插入資料id是" + resultSet.getInt(1));
return resultSet.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (resultSet != null)
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (preparedStatement != null)
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (connection != null)
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return 0;
}
優化不大,我們再引入一個第三方jar包commons-dbutils-1.6.jar
。
2.7 commons-dbutils操作資料庫
DbUtils是一個為簡化JDBC操作的小類庫,它的核心程式碼是QueryRunner和ResultSetHandler,通過使用這兩個類可以大幅簡化dao內的程式碼。
2.7.1 closeQuietly
commons-dbutils裡提供close()方法,我們剛剛的dao程式碼裡要關閉ResultSet、PreparedStatement、Connection之前,都必須判斷是否為NULL,也必須要try{}catch{},使用commons-dbutils就能簡單關閉ResultSet、PreparedStatement、Connection:
DbUtils.closeQuietly(resultSet);
DbUtils.closeQuietly(preparedStatement);
DbUtils.closeQuietly(connection);
2.7.2 QueryRunner做增刪改查
commons-dbutils提供了QueryRunner類來簡化資料庫操作,原本複雜的插入操作可以簡化成一句話:
return new QueryRunner().insert(connection,
"insert into type (name,type)values(?,?)",
new ScalarHandler<Long>(),name,type)
.intValue();
刪除操作:
new QueryRunner().update(connection, "delete from type where id=?",id);
更新操作:
new QueryRunner().update(connection,
"update type set name=?,type=? where id=?",name,type,id);
查詢操作:
return new QueryRunner().query(connection,
"select * from type where id=?",
new BeanHandler<>(Type.class),id);
2.7.8 ResultSetHandler將查詢資料注入到javaBean裡
commons-dbutils還提供了一個ResultSetHandler,可以很方便的將資料庫查詢出來的資料注入到javaBean中,省去了從resultSet裡不停get、set的操作。
- 查詢單個javaBean:BeanHandler;
- 查詢一組javaBean:BeanListHandler;
- 查詢單個欄位:ScalarHandler;
查詢一組javabean的程式碼如下:
public List<Type> getList(){
Connection connection = null;
try {
connection = DBUtil.getcConnection();
return new QueryRunner().query(connection, "select * from type", newBeanListHandler<>(Type.class));
} catch (Exception e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(connection);
}
return null;
}
這樣我們改造一下TypeDao.java:
package cn.funsoftware.Lesson.dao;
import java.sql.Connection;
import java.util.List;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import cn.funsoftware.Lesson.bean.Type;
import cn.funsoftware.Lesson.utils.DBUtil;
public class TypeDao2 {
public int add(String name, int type) {
Connection connection = null;
try {
connection = DBUtil.getcConnection();
return new QueryRunner().insert(connection, "insert into type (name,type)values(?,?)",
new ScalarHandler<Long>(), name, type).intValue();
} catch (Exception e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(connection);
}
return 0;
}
public void del(int id) {
Connection connection = null;
try {
connection = DBUtil.getcConnection();
new QueryRunner().update(connection, "delete from type where id=?", id);
} catch (Exception e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(connection);
}
}
public void update(int id, String name, int type) {
Connection connection = null;
try {
connection = DBUtil.getcConnection();
new QueryRunner().update(connection, "update type set name=?,type=? where id=?", name, type, id);
} catch (Exception e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(connection);
}
}
public Type getById(int id) {
Connection connection = null;
try {
connection = DBUtil.getcConnection();
return new QueryRunner().query(connection, "select * from type where id=?", new BeanHandler<>(Type.class),
id);
} catch (Exception e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(connection);
}
return null;
}
public List<Type> getList(){
Connection connection = null;
try {
connection = DBUtil.getcConnection();
return new QueryRunner().query(connection, "select * from type", new BeanListHandler<>(Type.class));
} catch (Exception e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(connection);
}
return null;
}
}
和之前的TypeDao對比一下,是不是節省很多操作?
相關推薦
javaWeb實戰教程4-jdbc連線資料庫和junit單元測試
javaWeb實戰教程 2.5 junit單元測試 我們在平時做程式碼時,每完成一個方法都需要先測試再提交,在java中比較常用的一個測試方法就是使用junit。 首先在專案中加入junit的jar包:junit-4.7.jar;將jar包複製到W
JDBC連線資料庫和查詢
/* JDBC工作過程: 1.載入驅動,建立連線(載入驅動是靠DriverManager,並且通過DriverManager獲取連線Connection) 2.建立語句物件(通過Connection建立Statement用於執行sql語句) 3.執行SQL語句 4.處理結
Eclipse使用(七)—— 使用Eclipse建立JavaWeb專案並使用JDBC連線資料庫實現簡單的登陸註冊功能
一、建立資料庫表(這裡使用的是Mysql5.7) DDL語句如下: CREATETABLE `tb_user` ( `u_id` int(11) NOTNULL AUTO_INCREMENT COMMENT '使用者編號', `u_username
JDBC連線資料庫工具類以及測試
1. 資料庫連線工具程式碼 package com.zzm.db; import java.sql.*; /** * Created by ming on 2017/6/13. */ public class DBUtil { //載入驅動 private f
完整java開發中JDBC連線資料庫程式碼和步驟
宣告:來自Hongten(部落格園) JDBC連線資料庫 建立一個以JDBC連線資料庫的程式,包含7個步驟: 1、載入JDBC驅動程式: 在連線資料庫之前,首先要載入想要連線的資料庫的驅動到JVM(Java虛擬機器), 這通過java.lang
JDBC —— 簡單的連線資料庫和封裝
連線資料庫,並讀取表裡的內容 eclipse連線資料庫的一般過程是: 1,載入JDBC驅動(jar驅動包自己去下,這裡有匯入jar到eclipse的方法Eclipse下匯入外部jar包的3種方式) 2,建立資料庫連線(Connection介面) 3,建立
4種JDBC連線資料庫的方法及其特點
1 JDBC-ODBC橋的方式。 這種方式不適合程式的重用與維護,不推薦使用。需要資料庫的ODBC驅動。 Jdbc-odbc橋是sun公司提供的,是jdk提供的的標準api。這種型別的驅動實際是把所有
jdbc連線資料庫的優化和防止注入
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException;
JDBC連線資料庫步驟和JDBC常用API
JDBC連線資料庫步驟 第一步:載入驅動類: Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 第二步:使用DriverManager的getConnection方法建立connection物件
使用JDBC連線資料庫並且呼叫儲存過程和執行SQL語句
JDBC呼叫資料庫: package com.hthk.iisz.util; import java.sql.Connection; import java.sql.DriverManager; public class SqlServerConnectionzUtil
微服務分散式事務實戰(五)準備資料庫和建立第一個微服務
1)資料庫準備 在資料庫中mysql 分別建立2個數據庫forum1和forum2 forum1 下建立表block forum2下建立表Theme sql程式碼如下: 1 資料庫1Forum1: CREATE DATABASE IF NOT EXISTS forum1; USE forum
JAVA JDBC 連線資料庫程式碼
package ora; import java.sql.Connection; import java.sql.DriverManager; public class springhead { //驅動程式就是之前在classpath中配置的JDBC的驅動程式的JAR 包中 publ
jsp資料庫(一、使用jdbc連線資料庫)
步驟: 一、載入驅動程式 Class.forName("sun.jdbc.odbc.jdbcOdbcDriver"); 二、建立連線物件 Connection conn = DriverManager.getConnection("主機名","使用者名稱","密碼");
Jemter使用JDBC連線資料庫
趁著上一篇文章用的jdbc的驅動jar包還在,索性就再用Jemter連線一下資料庫 環境:mysql (任意版本);jemter(任意版本);jdbc驅動jar包; 1.建立資料庫,建表,插入資料,以備jemter使用; mysql>create database te
JAVA WEB JDBC連線資料庫
桂 林 理 工 大 學 實 驗 報 告 班級 軟體16-1班 學號 3162052051116 姓名 張識虔 同組實驗者 &
使用jdbc連線資料庫時的一些錯誤
如果使用了mysql8.0以上的版本 異常資訊: 你如果用的包是以前的包的話,會提示使用caching_sha2_password 或者是 Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class i
JDBC連線資料庫總結
1.什麼是JDBC? JDBC(Java DataBase Connectivity)就是Java資料庫連線,說白了就是利用Java語言來操縱資料庫。原來我們操縱資料庫是在控制檯使用SQL語句來操縱資料庫的,JDBC就是用Java語言向資料庫傳送SQL語句。 2.
簡單實現jdbc連線資料庫工具類
第一步:匯入連線mysql資料庫所需要的jar包 第二步:實現一個簡單的jdbc連線資料庫工具類 package jdbc; import java.sql.Connection; import java.sql.DriverManager; import ja
使用jdbc連線資料庫中文亂碼問題
今天在學習jdbc時做了一個專案,專案主要實現的功能是通過jdbc連線資料庫,進行新增和查詢圖書館書籍。過程中遇到了新增中文到資料庫的亂碼問題,跟大家分享一下解決方案: 一.新增的時候是否有報錯(沒有的話直接繞道到二) 如果
JavaWeb學習筆記6——JDBC連線MySql進行增刪改查並分頁顯示
資料庫的增、刪、改、查是非常重要的操作,只要程式是關於資料庫的操作,無論程式大小,歸根結底都是這4種操作的使用。 連線MySql資料庫的過程: 1、註冊驅動 DriverManager.registerDriver(new com.mysql.jdbc.Driver()