java資料庫 JDBC的Dao模式(適合初學者)
java 連線資料庫首先要匯入一個jar包
我們來了解一下什麼是jdbc
其實JDBC(Java DataBase Connectivity,java資料庫連線)是一種用於執行SQL語句的Java AP
讀下面程式碼需要大概瞭解Statement常用的方法:
ResultSet executeQuery(String sql):執行SQL查詢並且獲取ResultSet物件
Int executeUpdate(String sql):可以執行插入、刪除、更新等操作,返回值是執行該操作所影響的行數
Boolean execute(String sql):可以執行任意SQL語句,然後獲得一個布林值,表示是否返回ResultSet
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; /** * *@desc JDBC的基本操作 *@author anthor *@time **/ public class Test { public static void main(String[] args) throws Exception { String sql=" select * from user "; //1.載入驅動 Class.forName("com.mysql.jdbc.Driver"); //2.指定使用者名稱和密碼 Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/table?useUnicode=true&characterEncoding=utf-8", "root","root" ); if (!conn.isClosed()) //3.獲取連線 { System.out.println("連線成功了"); //4.建立Statement物件 Statement stmt = conn.createStatement(); //5.執行sql語句 ResultSet rs = stmt.executeQuery(sql); //6.展示結果集 while (rs.next()) { System.out.println(rs.getString("id")+"\t"+rs.getString("name")); } //7.關閉物件 rs.close(); stmt.close(); conn.close(); } }
這只是一個簡單的查詢的操作
JDBC的Dao模式 實質上就是在上面程式碼中 去重構程式碼 從而達到
1.隔離業務邏輯程式碼和資料訪問程式碼
2.隔離不同資料庫的實現
的作用
Dao模式: 介面 實現類 測試類
下面程式碼是實現基本Dao模式的介面
import java.sql.SQLException;
import java.util.List;
import java.util.Map;public interface IDao {
public List<Map<String, Object>> executeQueryForList(String sql) throws Exception, SQLException;
public Map<String, Object> executeQueryForMap(String sql) throws Exception, SQLException;public int executeQueryForCount(String sql) throws ClassNotFoundException, SQLException;
public int executeUpdate(String sql) throws Exception, SQLException;
}
實現類
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.sql.Types;public class Dao implements IDao{
public static String diverName="com.mysql.jdbc.Driver";
public static String url = "jdbc:mysql://localhost:3306/tab?useUnicode=true&characterEncoding=UTF-8";
public static String userName="root";
public static String password="root";
/**
* @return 1.獲取連線
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConnection() throws ClassNotFoundException,SQLException {
Class.forName(diverName);//載入
//指定使用者名稱和密碼
Connection conn = DriverManager.getConnection(url, userName,password);
return conn;
}
/**
* @deac 2.查詢資料
* @param conn
* @param sql
* @throws SQLException
* @throws ClassNotFoundException
*/
public List<Map<String, Object>> executeQueryForList(String sql) throws SQLException, ClassNotFoundException {
System.err.println(sql);
Connection conn = getConnection();
//建立Statement物件
Statement stmt = conn.createStatement();
//執行sql語句
ResultSet rs = stmt.executeQuery(sql);
List<Map<String, Object>> list = rsToList(rs);
closeConnection(conn, stmt, rs);//關閉
return list;
}
/**
* @desc 2 .將rs轉換為List<map>
* @param rs
* @return
* @throws SQLException
*/
private List<Map<String, Object>> rsToList(ResultSet rs) throws SQLException{
//初始化list物件
List<Map<String, Object>> row=new ArrayList<Map<String,Object>>();
while (rs.next()) {//判斷
//建立map容器
Map<String, Object> col =new HashMap<String, Object>();
for (int i = 1; i <=rs.getMetaData().getColumnCount(); i++) {
//判斷資料型別
switch (rs.getMetaData().getColumnType(i)) {
case Types.VARCHAR:
col.put(rs.getMetaData().getColumnName(i), rs.getString(i));
break;
case Types.INTEGER:
col.put(rs.getMetaData().getColumnName(i), rs.getInt(i));
break;
default:
break;
}
}
//新增map資料
row.add(col);
}
return row;
}
/**
* @desc 3.查詢操作:獲取一條資料
* @param sql
* @return
* @throws Exception
* @throws SQLException
*/
public Map<String, Object> executeQueryForMap(String sql) throws Exception, SQLException
{
System.err.println(sql);
Connection conn = Dao.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
List<Map<String, Object>> list=this.rsToList(rs);
this.closeConnection(conn, stmt, rs);
if (!list.isEmpty())
{
return list.get(0);
}
return null;
}
/**
* @desc 4.查詢操作:獲取總記錄數
* @param sql
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public int executeQueryForCount(String sql) throws ClassNotFoundException, SQLException{
System.err.println(sql);
//連結資料庫
Connection conn = Dao.getConnection();
//建立Statement物件
Statement stmt = conn.createStatement();
//執行sql語句
ResultSet rs = stmt.executeQuery(sql);
int count = 0;
if (rs.next()) {
count = count+rs.getInt(1);
}
this.closeConnection(conn, stmt, rs);
return count;
}
/**
* @desc 5.執行新增,修改,刪除操作
* @param sql
* @return
* @throws Exception
* @throws SQLException
*/
public int executeUpdate(String sql) throws Exception, SQLException
{
System.err.println(sql);
Connection conn = Dao.getConnection();//連線
Statement stmt = conn.createStatement();//建立
int count = stmt.executeUpdate(sql);//執行
this.releaseConnection(conn, stmt);//關閉
return count;
}
/**
* @desc 6.關閉連線:關閉兩個物件
* @param conn
* @param stmt
* @throws SQLException
*/
private void releaseConnection(Connection conn, Statement stmt) throws SQLException {
try {
//判斷是否為空
if (stmt!=null)
{
stmt.close();
}
if (conn!=null)
{
conn.close();
}
}
catch (SQLException e)
{
throw new SQLException("資料庫關閉異常");
}
}
/**
* @desc 7.關閉連線
* @param conn
* @param stmt
* @param rs
* @throws SQLException
*/
public void closeConnection(Connection conn, Statement stmt,
ResultSet rs) throws SQLException {
try {
if (rs!=null) {
rs.close();
}
if (stmt!=null) {
stmt.close();
}
if (conn!=null) {
conn.close();
}
} catch (SQLException e) {
throw new SQLException("資料關閉異常!");
}
}
}
測試類
public class CeShi {
public static void main(String[] args) throws Exception
{
IDao dao = new Dao();
String sql = " select * from table01 where id='01' ";
List<Map<String, Object>> list = dao.executeQueryForList(sql);
for (Map<String, Object> map : list) {
System.out.println(map);
}
// int count = dao.executeUpdate(sql);
// System.out.println(count!=0?"執行成功!":"執行失敗!");
}
}
下面普及一下JDBC的常用的關鍵字
1.DriverManager:依據資料庫的不同,管理JDBC驅動
2.Connection:負責連線資料庫並且擔任傳送資料庫的任務
3.Statement:由Connection產生、負責執行SQL語句
4.ResultSet:負責儲存Statement執行後所產生的查詢結果