下面直接貼代碼吧,實體類我就不貼了
獲取數據庫連接的工具類
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBUtil {
// 驅動名稱 這裏是sqlserver驅動
private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
// 數據庫地址 127.0.0.1表示本地,
//1433是sqlserver默認的端口,food_db是要鏈接的數據庫
private static final String URL = "jdbc:sqlserver://127.0.0.1:1433;databasename=food_db";
// 用戶名
private static final String USER = "admin";
// 密碼
private static final String PASS = "123456";
//在靜態塊中加載數據庫連接驅動
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//得到數據庫連接的方法
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(URL, USER, PASS);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//關閉連接的方法
public static void closeAll(Connection conn, Statement stmt, ResultSet rs) {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//測試 打印下數據庫連接是否正常得到
public static void main(String[] args) {
System.out.println(getConnection());
}
}
//通過JdbcTemplate操作的方式
package dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import util.DBUtil;
import bean.Account;
import bean.Trade;
public class BankDaoImpl {
//得到JdbcTemplate對象,調用DBUtil.getDataSource()得到數據庫連接
private JdbcTemplate temp = new JdbcTemplate(DBUtil.getDataSource());
//查詢指定條件的數據,Account實體類我就不寫了
public Account login(Account a) {
//需要執行的sql語句 下面的Account實體類我就不寫了
String sql = "select * from account where AccountID=? and password=? ";
List list = this.temp.query(sql, new Object[] { a.getAccountID(),a.getPassword() },
new RowMapper() {
public Object mapRow(ResultSet rs, int arg1) throws SQLException {
Account a = new Account();
a.setRemaining(rs.getDouble("remaining"));//獲取字段名爲remaining的數據
a.setAccountID(rs.getString("accountid"));//獲取字段名爲accountid的數據
a.setPassword(rs.getString("password"));//獲取字段名爲password的數據
return a;
}
});
if (list.size() > 0){
return (Account) list.get(0);
}
return null;
}
//查詢多個對象方法,Trade跟Account實體類我就不寫了
public List<Trade> selectByTime(String a, Date time1, Date time2) {
String sql = "select * from trade where accountid=? and TradeTime between ? and ? ";
return this.temp.query(sql, new Object[] { a, time1, time2 },
new RowMapper() {
public Object mapRow(ResultSet rs, int arg1)throws SQLException {
Trade t = new Trade();
t.setId(rs.getInt("id"));
Account a = new Account();
a.setAccountID(rs.getString("accountid"));
t.setAccount(a);
t.setTradeDigest(rs.getString("tradeDigest"));
t.setTradeMoney(rs.getDouble("tradeMoney"));
t.setTradeTime(rs.getDate("tradeTime"));
t.setTradeType(rs.getString("tradeType"));
return t;
}
});
}
//查詢單個對象方法,Account實體類我就不寫了
public Account selectRemaining(String aid) {
String sql = "select * from Account where accountid=?";
List list= this.temp.query(sql,new Object[] { aid },
new RowMapper() {
public Object mapRow(ResultSet rs, int arg1)
throws SQLException {
Account a = new Account();
a.setAccountID(rs.getString("accountid"));
a.setRemaining(rs.getDouble("remaining"));
return a;
}
});
if(list.size()==0){
return null;
}
return (Account) list.get(0);
}
//修改方法,返回受影響的行數
public int trade(String aid, double money) {
String sql = "update account set remaining=remaining+? where accountid=? ";
return this.temp.update(sql, new Object[] { money, aid });
}
//新增方法,返回受影響的行數(seq_trede.nextval數據庫序列,sysdate獲取當前系統時間)
public int insertTrade(Trade t) {
String sql = "insert into trade values(seq_trede.nextval,?,?,?,sysdate,?)";
return this.temp.update(sql, new Object[] {t.getAccount().getAccountID(),
t.getTradeType(),t.getTradeMoney(), t.getTradeDigest() });
}
}
//不通過JdbcTemplate對象操作
package util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class Template {
// 針對任何表的查詢
public void query(String sql, Object[] params) {
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
conn = DBUtil.getConnection();//調用上面的DBUtil類中getConnection()方法獲取鏈接
try {
pst = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
pst.setObject(i + 1, params[i]);
}
}
rs = pst.executeQuery();
//元數據類型
ResultSetMetaData rsmd = rs.getMetaData();
// 得到結果集共有幾列
int count = rsmd.getColumnCount();
while (rs.next()) {// 遍歷行
for (int i = 0; i < count; i++) {
//我這裏在控制檯打印下,可以根據自己的需求封裝
System.out.print(rs.getObject(i + 1) + ",");
}
System.out.println();//打印換行
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.closeAll(conn, pst, rs);
}
}
// 針對任何表的增,改,刪,返回受影響的行數
// sql是要執行的SQL語句
// Object[]保存的是SQL語句要用到的參數值
public int update(String sql, Object[] params) {
int rows = 0;//記錄受影響的行數
Connection conn = null;
PreparedStatement pst = null;
conn = DBUtil.getConnection();//調用上面的DBUtil類中getConnection()方法獲取鏈接
try {
pst = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
pst.setObject(i + 1, params[i]);
}
}
rows = pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtil.closeAll(conn, pst, null);
}
return rows;
}
}