滿漢樓01-2 4.功能實現01 4.1導入驅動和工具類 4.1.1導入驅動 首先將連接mysql的相關jar包引入項目中,分別右鍵,點擊add as library 4.1.2導入工具類Utility 準備工具類Utility,提高開發效率,並搭建整個項目的整體架構 在實際開發中,公司都會提供相應 ...
滿漢樓01-2
4.功能實現01
4.1導入驅動和工具類
4.1.1導入驅動
首先將連接mysql的相關jar包引入項目中,分別右鍵,點擊add as library
4.1.2導入工具類Utility
準備工具類Utility,提高開發效率,並搭建整個項目的整體架構
在實際開發中,公司都會提供相應的工具類和開發庫,可以提高效率
package com.hspedu.mhl.utils;
/**
工具類的作用:
處理各種情況的用戶輸入,並且能夠按照程式員的需求,得到用戶的控制台輸入。
*/
import java.util.*;
/**
*/
public class Utility {
//靜態屬性。。。
private static Scanner scanner = new Scanner(System.in);
/**
* 功能:讀取鍵盤輸入的一個菜單選項,值:1——5的範圍
* @return 1——5
*/
public static char readMenuSelection() {
char c;
for (; ; ) {
String str = readKeyBoard(1, false);//包含一個字元的字元串
c = str.charAt(0);//將字元串轉換成字元char類型
if (c != '1' && c != '2' &&
c != '3' && c != '4' && c != '5') {
System.out.print("選擇錯誤,請重新輸入:");
} else break;
}
return c;
}
/**
* 功能:讀取鍵盤輸入的一個字元
* @return 一個字元
*/
public static char readChar() {
String str = readKeyBoard(1, false);//就是一個字元
return str.charAt(0);
}
/**
* 功能:讀取鍵盤輸入的一個字元,如果直接按回車,則返回指定的預設值;否則返回輸入的那個字元
* @param defaultValue 指定的預設值
* @return 預設值或輸入的字元
*/
public static char readChar(char defaultValue) {
String str = readKeyBoard(1, true);//要麼是空字元串,要麼是一個字元
return (str.length() == 0) ? defaultValue : str.charAt(0);
}
/**
* 功能:讀取鍵盤輸入的整型,長度小於2位
* @return 整數
*/
public static int readInt() {
int n;
for (; ; ) {
String str = readKeyBoard(2, false);//一個整數,長度<=2位
try {
n = Integer.parseInt(str);//將字元串轉換成整數
break;
} catch (NumberFormatException e) {
System.out.print("數字輸入錯誤,請重新輸入:");
}
}
return n;
}
/**
* 功能:讀取鍵盤輸入的 整數或預設值,如果直接回車,則返回預設值,否則返回輸入的整數
* @param defaultValue 指定的預設值
* @return 整數或預設值
*/
public static int readInt(int defaultValue) {
int n;
for (; ; ) {
String str = readKeyBoard(10, true);
if (str.equals("")) {
return defaultValue;
}
//異常處理...
try {
n = Integer.parseInt(str);
break;
} catch (NumberFormatException e) {
System.out.print("數字輸入錯誤,請重新輸入:");
}
}
return n;
}
/**
* 功能:讀取鍵盤輸入的指定長度的字元串
* @param limit 限制的長度
* @return 指定長度的字元串
*/
public static String readString(int limit) {
return readKeyBoard(limit, false);
}
/**
* 功能:讀取鍵盤輸入的指定長度的字元串或預設值,如果直接回車,返回預設值,否則返回字元串
* @param limit 限制的長度
* @param defaultValue 指定的預設值
* @return 指定長度的字元串
*/
public static String readString(int limit, String defaultValue) {
String str = readKeyBoard(limit, true);
return str.equals("")? defaultValue : str;
}
/**
* 功能:讀取鍵盤輸入的確認選項,Y或N
* 將小的功能,封裝到一個方法中.
* @return Y或N
*/
public static char readConfirmSelection() {
System.out.print("確認是否預訂(Y/N): ");
char c;
for (; ; ) {//無限迴圈
//在這裡,將接受到字元,轉成了大寫字母
//y => Y n=>N
String str = readKeyBoard(1, false).toUpperCase();
c = str.charAt(0);
if (c == 'Y' || c == 'N') {
break;
} else {
System.out.print("選擇錯誤,請重新輸入:");
}
}
return c;
}
/**
* 功能: 讀取一個字元串
* @param limit 讀取的長度
* @param blankReturn 如果為true ,表示 可以讀空字元串。
* 如果為false表示 不能讀空字元串。
*
* 如果輸入為空,或者輸入大於limit的長度,就會提示重新輸入。
* @return
*/
private static String readKeyBoard(int limit, boolean blankReturn) {
//定義了字元串
String line = "";
//scanner.hasNextLine() 判斷有沒有下一行
while (scanner.hasNextLine()) {
line = scanner.nextLine();//讀取這一行
//如果line.length=0, 即用戶沒有輸入任何內容,直接回車
if (line.length() == 0) {
if (blankReturn) return line;//如果blankReturn=true,可以返回空串
else continue; //如果blankReturn=false,不接受空串,必須輸入內容
}
//如果用戶輸入的內容大於了 limit,就提示重寫輸入
//如果用戶如的內容 >0 <= limit ,我就接受
if (line.length() < 1 || line.length() > limit) {
System.out.print("輸入長度(不能大於" + limit + ")錯誤,請重新輸入:");
continue;
}
break;
}
return line;
}
}
4.1.3導入工具類JDBCUtilsByDruid
package li.dao_.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 基於Druid資料庫連接池的工具類
*/
public class JDBCUtilsByDruid {
private static DataSource ds;
//在靜態代碼塊完成ds的初始化
//靜態代碼塊在載入類的時候只會執行一次,因此數據源也只會初始化一次
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src\\druid.properties"));
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//編寫getConnection方法
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//關閉連接(註意:在資料庫連接池技術中,close不是真的關閉連接,而是將Connection對象放回連接池中)
public static void close(ResultSet resultSet, Statement statemenat, Connection connection) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statemenat != null) {
statemenat.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
- 德魯伊的配置文件,放在src目錄下
#key=value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mhl?rewriteBatchedStatements=true
#url=jdbc:mysql://localhost:3306/mhl
username=root
password=123456
#initial connection Size
initialSize=10
#min idle connecton size
minIdle=5
#max active connection size
maxActive=50
#max wait time (5000 mil seconds)
maxWait=5000
4.1.4導入BasicDAO
package com.li.mhl.dao;
import com.li.mhl.utils.JDBCUtilsByDruid;
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 java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
/**
* 開發BasicDAO,是其他DAO的父類
*/
public class BasicDAO<T> {//泛型指定具體的類型
private QueryRunner qr = new QueryRunner();
//開發通用的dml方法,針對任意的表
/**
* @param sql 傳入的SQL語句,可以有占位符?
* @param parameters 傳入占位符?的具體的值,可以是多個
* @return 返回的值是受影響的行數
*/
public int update(String sql, Object... parameters) { //可變參數 Object… parameters
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
int update = qr.update(connection, sql, parameters);
return update;
} catch (SQLException e) {
throw new RuntimeException(e);//將一個編譯異常轉變為運行異常
} finally {
JDBCUtilsByDruid.close(null, null, connection);
}
}
//返回多個對象(即查詢的結果是多行),針對任意的表(多行多列)
/**
* @param sql 傳入的SQL語句,可以有占位符?
* @param clazz 傳入一個類的Class對象,比如 Actor.class[底層需要通過反射來創建Javabean對象]
* @param parameters 傳入占位符?的具體的值,可以是多個
* @return 根據傳入的class對象 Xxx.class 返回對應的ArrayList集合
*/
public List<T> queryMulti(String sql, Class<T> clazz, Object... parameters) {
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
return qr.query(connection, sql, new BeanListHandler<T>(clazz), parameters);
} catch (SQLException e) {
throw new RuntimeException(e);//將一個編譯異常轉變為運行異常
} finally {
JDBCUtilsByDruid.close(null, null, connection);
}
}
//查詢單行結果 的通用方法(單行多列)
public T querySingle(String sql, Class<T> clazz, Object... parameters) {
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
return qr.query(connection, sql, new BeanHandler<T>(clazz), parameters);
} catch (SQLException e) {
throw new RuntimeException(e);//將一個編譯異常轉變為運行異常
} finally {
JDBCUtilsByDruid.close(null, null, connection);
}
}
//查詢單行單列的方法,即返回單值的方法
public Object queryScalar(String sql, Object... parameters) {
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
return qr.query(connection, sql, new ScalarHandler(), parameters);
} catch (SQLException e) {
throw new RuntimeException(e);//將一個編譯異常轉變為運行異常
} finally {
JDBCUtilsByDruid.close(null, null, connection);
}
}
}
進過測試,工具類使用正常