customerdao.java

来自「struts框架的演示示例,虽然简单但很有启发性,值得一看」· Java 代码 · 共 86 行

JAVA
86
字号
package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import po.Customer;

public class CustomerDao {
	private Connection conn = null;	
	public void initConnection(){//初始化数据库连接
		try{
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			conn = DriverManager.getConnection("jdbc:odbc:School","scott","tiger");
		}catch(Exception ex){ex.printStackTrace();}
	}
	
	public boolean insertCustomer(Customer cus){
		String sql = "INSERT INTO T_CUSTOMER(ACCOUNT,PASSWORD,CNAME,CBALANCE) VALUES(?,?,?,?)";
		try{
			initConnection();
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, cus.getAccount());
			ps.setString(2, cus.getPassword());
			ps.setString(3, cus.getCname());
			ps.setDouble(4, cus.getCbalance());
			ps.executeUpdate();
			return true;			
		}catch(Exception ex){ex.printStackTrace();}
		finally{
			closeConnection();
		}
		return false;
	} 	
	
	public boolean updateCustomer(Customer cus){
		String sql = "UPDATE T_CUSTOMER SET PASSWORD=?,CNAME=?,CBALANCE=? WHERE ACCOUNT=?";
		try{
			initConnection();
			PreparedStatement ps = conn.prepareStatement(sql);			
			ps.setString(1, cus.getPassword());
			ps.setString(2, cus.getCname());
			ps.setDouble(3, cus.getCbalance());
			ps.setString(4, cus.getAccount());
			ps.executeUpdate();
			return true;			
		}catch(Exception ex){ex.printStackTrace();}
		finally{
			closeConnection();
		}
		return false;
	} 	
	
	public Customer getCustomerByAccount(String account){
		String sql = "SELECT ACCOUNT,PASSWORD,CNAME,CBALANCE FROM T_CUSTOMER WHERE ACCOUNT=?";
		try{
			initConnection();
			PreparedStatement ps = conn.prepareStatement(sql);			
			ps.setString(1, account);
			ResultSet rs = ps.executeQuery();
			if(rs.next()){
				Customer cus = new Customer();
				cus.setAccount(rs.getString("ACCOUNT"));
				cus.setPassword(rs.getString("PASSWORD"));
				cus.setCname(rs.getString("CNAME"));
				cus.setCbalance(rs.getDouble("CBALANCE"));
				return cus;
			}
		}catch(Exception ex){ex.printStackTrace();}
		finally{
			closeConnection();
		}
		return null;
	} 	
	
	public void closeConnection(){
		try{
			if(conn!=null){
				conn.close();
				conn = null;
			}
		}catch(Exception ex){ex.printStackTrace();}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?