数据库访问JavaBean

数据库访问JavaBean(以添加、查询为例)

1.数据库连接对象工具类的设计与实现

(1).在类路径src下建立文件db.properties(file形式)

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bbb?useUnicode=true&characterEncoding=UTF-8
user=root
password=2411030483

(2).建立一个可以获取连接和释放资源的工具类

package java第十周;

import java.util.Properties;
import java.sql.*;

public class JdbcUtil {
private static String driver;
private static String url;
private static String user;
private static String password;
private static Properties pr=new Properties();
private JdbcUtil(){}
static{
	try{
		pr.load(JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties"));
		driver=pr.getProperty("driver");
		url=pr.getProperty("url");
		user=pr.getProperty("user");
		password=pr.getProperty("password");
		Class.forName(driver);
	}catch(Exception e)
	{
		throw new ExceptionInInitializerError(e);
	}
}
public static Connection getConnection()throws Exception
{
	return DriverManager.getConnection(url,user,password);
}
public static void free(ResultSet rs,Statement st,Connection conn) throws Exception{
	if(rs!=null){rs.close();}
	if(st!=null){st.close();}
	if(conn!=null){conn.close();}
	
}
}

2.数据库访问Javabean的设计与实现

(1).创建实体类User,实现记录信息对象化。

package java第十周;

public class User {
private int userid;
private String username,sex;

public User(int userid, String username, String sex) {
	super();
	this.userid = userid;
	this.username = username;
	this.sex = sex;
}

public User() {
	super();
	// TODO Auto-generated constructor stub
}

public int getUserid() {
	return userid;
}

public void setUserid(int userid) {
	this.userid = userid;
}

public String getUsername() {
	return username;
}

public void setUsername(String username) {
	this.username = username;
}

public String getSex() {
	return sex;
}

public void setSex(String sex) {
	this.sex = sex;
}

}

(2).在User.java的基础上创建类UserDao.java封装基本的数据库操作。

package java第十周;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
public void add(User user)throws Exception
{
	Connection conn=(Connection) JdbcUtil.getConnection();
	String sql="insert into student(id,name,sex) values(?,?,?)";
	PreparedStatement pstmt=(PreparedStatement) conn.prepareStatement(sql);
	pstmt.setInt(1,user.getUserid());
	pstmt.setString(2,user.getUsername());
	pstmt.setString(3,user.getSex());
	pstmt.executeUpdate();
	JdbcUtil.free(null,pstmt,conn);
}
public void update(User user)throws Exception
{
	Connection conn=(Connection) JdbcUtil.getConnection();
	String sql="update student set id=?,name=?,sex=?";
	PreparedStatement pstmt=(PreparedStatement) conn.prepareStatement(sql);
	pstmt.setInt(1,user.getUserid());
	pstmt.setString(2,user.getUsername());
	pstmt.setString(3,user.getSex());
	pstmt.executeUpdate();
	JdbcUtil.free(null,pstmt,conn);
}
public void delete(int userId)throws Exception
{
	Connection conn=(Connection) JdbcUtil.getConnection();
	String sql="delete from student where id=?";
	PreparedStatement pstmt=(PreparedStatement) conn.prepareStatement(sql);
	pstmt.setInt(1,userId);
	pstmt.executeUpdate();
	JdbcUtil.free(null,pstmt,conn);
}
public User findUserById(int userId)throws Exception
{
	Connection conn=(Connection) JdbcUtil.getConnection();
	User user=null;
	String sql="select * from student where id=?";
	PreparedStatement pstmt=(PreparedStatement) conn.prepareStatement(sql);
	pstmt.setInt(1,userId);
	ResultSet rs=pstmt.executeQuery();
	if(rs.next())
	{
		user=new User();
		user.setUserid(rs.getInt("id"));
		user.setUsername(rs.getString("name"));
		user.setSex(rs.getString("sex"));
	}
	JdbcUtil.free(rs, pstmt, conn);
	return user;
}
public List QueryAll() throws Exception
{
	Connection conn=(Connection) JdbcUtil.getConnection();
	List userList=new ArrayList();
	String sql="select * from student";
	PreparedStatement pstmt=(PreparedStatement) conn.prepareStatement(sql);
	ResultSet rs=pstmt.executeQuery();
	while(rs.next())
	{
		User user=new User();
		user.setUserid(rs.getInt("id"));
		user.setUsername(rs.getString("name"));
		user.setSex(rs.getString("sex"));
		userList.add(user);
	}
	JdbcUtil.free(rs, pstmt, conn);
	return userList;
}
}

3.在jsp中使用javabean访问数据库

1.提交页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




提交数据页面


编号:
姓名:
性别:

2.计算加工页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="java第十周.User" %>
        <%@ page import="java第十周.UserDao" %>
        <%@ page import="java.util.List" %>




接收数据并实现添加


<%
request.setCharacterEncoding("UTF-8");//设置字符编码,避免乱码
String id=request.getParameter("id");
String name=request.getParameter("name");
String sex=request.getParameter("sex");
int idd=Integer.parseInt(id);
User u=new User(idd,name,sex);
UserDao dao=new UserDao();
dao.add(u);
List  users=dao.QueryAll();
request.setAttribute("userslist", users);
%>


3.显示信息页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
        <%@ page import="java第十周.User" %>
        <%@ page import="java.util.List" %>




添加后显示数据


<%
request.setCharacterEncoding("UTF-8");//设置字符编码,避免乱码
List  users=(List )(request.getAttribute("userslist"));
for(int i=0;i");
}
%>

 

你可能感兴趣的:(java)