java封装JDBC操作数据库的方法:增、删、改、查

1.目录结构


2.需要依赖的jar

mysql-connector-java-5.1.42-bin.jar  MySQL数据库驱动的jar包

3.首先是对数据库的操作

首先是连接数据库,操作完成后再关闭数据库

package com.lykion.dao;

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

public class DBConn {

	private static Connection conn;
	private static PreparedStatement ps;
	private static ResultSet rs;
	/**
	 * 连接数据库
	 * @return 
	 */
	public static Connection getConnection() {
		try {
			Class.forName(Contants.driver);		//加载mysql驱动
			System.out.println(Contants.driver + "加载成功!");
		} catch (ClassNotFoundException e) {
			System.out.println(Contants.driver + "加载失败(╯﹏╰)b");
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection(Contants.url, Contants.username, Contants.password);		//连接数据库
			System.out.println(Contants.url + "连接成功!");
		} catch (SQLException e) {
			System.out.println(Contants.url + "连接失败(╯﹏╰)b");
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 关闭数据库连接
	 * @throws SQLException
	 */
	public static void closeConnection() {
		if(ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}		//关闭数据库
		}
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

4.连接数据库成功后,可以对数据库进行操作

package com.lykion.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DBUtil {

	/**
	 * 查询所有学生信息{多条查询}
	 * @return
	 */
	public static List<Student> getAllStudentInfo(){
		Connection conn = null;
		PreparedStatement ps = null;
//		Statement stmt;
		ResultSet rs = null;
		
		List<Student> stu = new ArrayList<Student>();
		
		try {
			conn = DBConn.getConnection();
			String sql = "SELECT * FROM student01";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()) {
				String sno = rs.getString("sno");
				String sname = rs.getString("sname");
				String dname = rs.getString("dname");
				String ssex = rs.getString("ssex");
				int cno = rs.getInt("cno");
				int mark = rs.getInt("mark");
				String type = rs.getString("type");
				Student st = new Student(sno, sname, dname, ssex, cno, mark, type);
				stu.add(st);
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return stu;
	}
	
	/**
	 * 通过学号Sno查询{单条查询}
	 * @param sno
	 * @return
	 */
	public static Student getStudentInfoBySno(String sno) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		Student stu = null;
		try {
			conn = DBConn.getConnection();
			String sql = "SELECT * FROM student01 WHERE sno=?";
			ps = conn.prepareStatement(sql);
			ps.setNString(1, sno);
			rs = ps.executeQuery();
			while(rs.next()) {
				String sno1 = rs.getString("sno");
				String sname = rs.getString("sname");
				String dname = rs.getString("dname");
				String ssex = rs.getString("ssex");
				int cno = rs.getInt("cno");
				int mark = rs.getInt("mark");
				String type = rs.getString("type");
				stu = new Student(sno1, sname, dname, ssex, cno, mark, type);
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(ps!= null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return stu;
	}
	
	/**
	 * 增加学生信息{插入学生信息}
	 * @param stu
	 */
	public static void insertStuInfo(Student stu) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = DBConn.getConnection();
			String sql = "INSERT INTO student01 (sno,sname,dname,ssex,cno,mark,type) VALUES(?,?,?,?,?,?,?)";
			ps = conn.prepareStatement(sql);
			//设置占位符对应的值
			ps.setString(1, stu.getSno());
			ps.setString(2, stu.getSname());
			ps.setString(3, stu.getDname());
			ps.setString(4, stu.getSsex());
			ps.setInt(5, stu.getCno());
			ps.setFloat(6, stu.getMark());
			ps.setString(7, stu.getType());
			int insertCount = ps.executeUpdate();
			System.out.println(isSuccess(insertCount));
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 根据Sno删除学生信息
	 * @param sno
	 */
	public static void deleteStuInfo(String sno) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = DBConn.getConnection();
			String sql = "DELETE FROM student01 WHERE sno = ?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, sno);
			int deleteCount = ps.executeUpdate();
			System.out.println(isSuccess(deleteCount));
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 修改学生信息
	 * @param stu
	 * @throws SQLException
	 */
	public static void modifyStuInfo(Student stu) throws SQLException {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = DBConn.getConnection();
			String sql = "UPDATE student01 SET sname=?, dname=?, ssex=?, cno=?, mark=?, type=? WHERE sno=?";
			ps = conn.prepareStatement(sql);
			//注意参数站位的位置
			//此处是通过序号sno去更新学生信息,所以sno的位置不是在第一个位置而是在最后一个位置
			ps.setString(1, stu.getSname());
			ps.setString(2, stu.getDname());
			ps.setString(3, stu.getSsex());
			ps.setInt(4, stu.getCno());
			ps.setFloat(5, stu.getMark());
			ps.setString(6, stu.getType());
			ps.setString(7, stu.getSno());
			
			int count = ps.executeUpdate();
			System.out.println(isSuccess(count));
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(conn != null) {
				conn.close();
			}
		}
	}
	
	/**
	 * 判断操作是否成功
	 * @param count
	 * @return
	 */
	public static String isSuccess(int count) {
		if(count > 0) {
			return "操作成功!";
		}else {
			return "操作失败";
		}
	}
	
	/**
	 * 增删改操作   {另一种封装增、删、查、改作方法}
	 * @param conn
	 * @param sql
	 * @param param
	 * @return
	 */
	public static int executeUpdate(Connection conn, String sql, Object[] param) {
		int result = 0;
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			if(param != null) {
				for(int i=0; i<param.length; i++) {
					ps.setObject(i+1, param[i]);
				}
			}
			result = ps.executeUpdate();
		}catch(Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
5.创建Student实体类

package com.lykion.dao;

public class Student {

	private String sno;
	private String sname;
	private String dname;
	private String ssex;
	private int cno;
	private int mark;
	private String type;
	
	public Student() {
		
	}
	
	public Student(String sno, String sname, String dname, String ssex, int cno, int mark, String type) {
		super();
		this.sno = sno;
		this.sname = sname;
		this.dname = dname;
		this.ssex = ssex;
		this.cno = cno;
		this.mark = mark;
		this.type = type;
	}
	
	public String getSno() {
		return sno;
	}
	public void setSno(String sno) {
		this.sno = sno;
	}
	
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	
	public String getDname() {
		return dname;
	}
	public void setDname(String dname) {
		this.dname = dname;
	}
	
	public String getSsex() {
		return ssex;
	}
	public void setSsex(String ssex) {
		this.ssex = ssex;
	}
	
	public int getCno() {
		return cno;
	}
	public void setCno(int cno) {
		this.cno = cno;
	}
	
	public float getMark() {
		return mark;
	}
	public void setMark(int mark) {
		this.mark = mark;
	}
	
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
}
6.常量类:

创建常量类的目的就是方便修改数据连接等其他信息的修改

package com.lykion.dao;
/**
* 常量
* @author Uker
*
*/
public class Contants {


public static final String url = "jdbc:mysql://localhost:3306/test";//数据库地址
public static final String username = "root";//数据库用户名
public static final String password = "123456";//数据库密码
public static final String driver = "com.mysql.jdbc.Driver";//mysql驱动
}

7.创建测试类

用来测试对数据库的操作是否成功

package com.lykion.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

public class MainTest {

	public static void main(String[] args) {
		Connection conn = DBConn.getConnection();
		System.out.println("conn:"+conn);
		
//		/**
//		 * 测试获取所有学生信息{多条查询}
//		 */
//		List<Student> stu = DBUtil.getAllStudentInfo();
//		Iterator<Student> it = stu.iterator();
//		while(it.hasNext()) {
//			Student st = it.next();
//			System.out.println(st.getSno() +","+ st.getSname() +","+ st.getDname() +","+ st.getSsex() +","+ st.getCno() +","+ st.getMark() +","+ st.getType());
//		}
		
//		/**
//		 * 测试根据Sno查询学生信息{单条查询}
//		 */
//		String sno = "9701";
//		Student stu = DBUtil.getStudentInfoBySno(sno);
//		System.out.println(stu.getSno() +","+ stu.getSname() +","+ stu.getDname() +","+ stu.getSsex() +","+ stu.getCno() +","+ stu.getMark() +","+ stu.getType());
		
//		/**
//		 * 测试添加学生信息{insert学生信息}
//		 */
//		Student stu = new Student("9805", "邓光", "工程造价", "男", 8, 85, "必修");
//		DBUtil.insertStuInfo(stu);
		
//		/**
//		 * 测试根据学号sno删除学生信息
//		 */
//		String sno = "9805";
//		DBUtil.deleteStuInfo(sno);
		
		/**
		 * 测试修改学生信息
		 */
//		UPDATE student01 SET sname='董存瑞',dname='工程造价',ssex='女',cno=5,mark=95,type='必须' WHERE sno='2017';
		Student stu = new Student("2017" ,"朱啸天", "计算机科学与软件工程", "男", 8, 85, "必修");
			try {
				DBUtil.modifyStuInfo(stu);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		
//		/**
//		 * 测试修改学生信息
//		 */
//		conn = DBConn.getConnection();
//		String sql = "UPDATE student01 SET sname = '老彭' WHERE sno = '9805'";
//		DBUtil.executeUpdate(conn, sql, null);
		
		DBConn.closeConnection();
	}
}



  • 14
    点赞
  • 82
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
经典java数据库封装类,package com.bjsxt.shopping.util; import java.sql.*; public class DB { public static Connection getConn() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost/shopping?user=root&password=root"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return conn; } public static PreparedStatement prepare(Connection conn, String sql) { PreparedStatement pstmt = null; try { if(conn != null) { pstmt = conn.prepareStatement(sql); } } catch (SQLException e) { e.printStackTrace(); } return pstmt; } public static PreparedStatement prepare(Connection conn, String sql, int autoGenereatedKeys) { PreparedStatement pstmt = null; try { if(conn != null) { pstmt = conn.prepareStatement(sql, autoGenereatedKeys); } } catch (SQLException e) { e.printStackTrace(); } return pstmt; } public static Statement getStatement(Connection conn) { Statement stmt = null; try { if(conn != null) { stmt = conn.createStatement(); } } catch (SQLException e) { e.printStackTrace(); } return stmt; } /* public static ResultSet getResultSet(Connection conn, String sql) { Statement stmt = getStatement(conn); ResultSet rs = getResultSet(stmt, sql); close(stmt); return rs; } */ public static ResultSet getResultSet(Statement stmt, String sql) { ResultSet rs = null; try { if(stmt != null) { rs = stmt.executeQuery(sql); } } catch (SQLException e) { e.printStackTrace(); } return rs; } public static void executeUpdate(Statement stmt, String sql) { try { if(stmt != null) { stmt.executeUpdate(sql); } } catch (SQLException e) { e.printStackTrace(); } } public static void close(Connection conn) { try { if(conn != null) { conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); } } public static void close(Statement stmt) { try { if(stmt != null) { stmt.close(); stmt = null; } } catch (SQLException e) { e.printStackTrace(); } } public static void close(ResultSet rs) { try { if(rs != null) { rs.close(); rs = null; } } catch (SQLException e) { e.printStackTrace(); } } }
以下是Java JDBC封装方法的示例: 1. 连接数据库 ```java public Connection getConnection() throws SQLException { String url = "jdbc:mysql://localhost:3306/testdb"; String username = "root"; String password = "password"; Connection conn = DriverManager.getConnection(url, username, password); return conn; } ``` 2. 询数据 ```java public List<Student> findAll() throws SQLException { List<Student> students = new ArrayList<>(); String sql = "SELECT * FROM student"; Connection conn = getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { Student student = new Student(); student.setId(rs.getInt("id")); student.setName(rs.getString("name")); student.setAge(rs.getInt("age")); student.setGender(rs.getString("gender")); student.setDepartment(rs.getString("department")); students.add(student); } return students; } ``` 3. 插入数据 ```java public int insert(Student student) throws SQLException { String sql = "INSERT INTO student(name, age, gender, department) VALUES (?, ?, ?, ?)"; Connection conn = getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, student.getName()); pstmt.setInt(2, student.getAge()); pstmt.setString(3, student.getGender()); pstmt.setString(4, student.getDepartment()); int result = pstmt.executeUpdate(); return result; } ``` 4. 更新数据 ```java public int update(Student student) throws SQLException { String sql = "UPDATE student SET name=?, age=?, gender=?, department=? WHERE id=?"; Connection conn = getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, student.getName()); pstmt.setInt(2, student.getAge()); pstmt.setString(3, student.getGender()); pstmt.setString(4, student.getDepartment()); pstmt.setInt(5, student.getId()); int result = pstmt.executeUpdate(); return result; } ``` 5. 除数据 ```java public int delete(int id) throws SQLException { String sql = "DELETE FROM student WHERE id=?"; Connection conn = getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id); int result = pstmt.executeUpdate(); return result; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值