JDBC学习笔记3(dao模式)(优化)

将执行sql语句的方法封装到JdbcUtil类中

package com.oracle.Util;

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

/**
 * 通用连接数据库
 * @author Shinelon
 *
 */
public class JdbcUtil {

	static String userName="root";
	static String password="tiger";
	static String url="jdbc:mysql://localhost:3306/test";
	
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() {
		Connection conn=null;
		try{
			conn=DriverManager.getConnection(url, userName, password);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 执行一个sql
	 * @param sql
	 * @param arg   sql语句需要绑定的参数值
	 * @return
	 */
	public static int executeSql(String sql,Object...arg) {
		int count=0;
		try(Connection conn=getConnection();
			PreparedStatement ps=conn.prepareStatement(sql);
			){
			for (int i=0;i<arg.length;i++) {
				ps.setObject(i+1,arg[i]);
			}
			count=ps.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}
		return count;
	}
	
	
}

此时的实现类代码就十分清爽:

package com.oracle.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;

import com.oracle.Util.JdbcUtil;
import com.oracle.vo.Account;

public class AccountDaoImpl implements AccountDao {
	
	String sql_insret="insert into account values (null,?,?)";
	String sql_delete="delete from account where accountid=?";
	String sql_update="update account set name=?,remain=? where accountid=?";
	@Override
	public void insert(Account account) {
		
		JdbcUtil.executeSql(sql_insret, account.getName(),account.getRemain());
	}

	@Override
	public void delete(Integer accountId) {
		
		JdbcUtil.executeSql(sql_delete,accountId);
	}

	@Override
	public boolean update(Account account) {
		return JdbcUtil.executeSql(sql_update, account.getName(),account.getRemain(),account.getAccountid())>0?true:false;
	}

}

猜你喜欢

转载自blog.csdn.net/Sunhongyu51/article/details/86145315