database class

本文提供了一个使用 Java 进行 MySQL 数据库操作的示例代码,包括连接数据库、添加、删除、更新学生信息及查询所有学生记录的功能实现。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class sql_con {

	PreparedStatement pst;
	Connection con;

	public Connection getConn() throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver");
		Connection con = DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/mydata?useUnicode=true&characterEncoding=utf-8", "root", "");
		return con;
	}

	public int addstu(Student stu) throws ClassNotFoundException, SQLException {
		con = getConn();
		String sql_in = "insert into student values(null, ?, ?)";
		PreparedStatement pst = con.prepareStatement(sql_in);
		pst.setString(1, stu.getName());
		pst.setInt(2, stu.getAge());
		int exi = pst.executeUpdate();
		pst.close();
		con.close();
		return exi;
	}

	public int delstu(int id) throws ClassNotFoundException, SQLException {
		con = getConn();
		String sql = "delete from student where id=?";
		pst = con.prepareStatement(sql);
		pst.setInt(1, id);

		int result = pst.executeUpdate();
		pst.close();
		con.close();
		return result;
	}

	public int udstu(Student stu) throws ClassNotFoundException, SQLException {
		con = getConn();
		String sql = "update student set name=?,age=? where id=?";
		pst = con.prepareStatement(sql);
		pst.setString(1, stu.getName());
		pst.setInt(2, stu.getAge());
		pst.setInt(3, stu.getId());

		int result = pst.executeUpdate();
		pst.close();
		con.close();
		return result;
	}

	public List<Student> queryAll() throws ClassNotFoundException, SQLException {
		con = getConn();
		String sql = "select * from student";
		pst = con.prepareStatement(sql);
		ResultSet rs = pst.executeQuery();

		List<Student> li = new ArrayList<Student>();
		while (rs.next()) {
			Student stu = new Student(rs.getInt(1), rs.getString(2), rs.getInt(3));
			li.add(stu);
		}
		pst.close();
		con.close();
		return li;
	}

	public Student querryByid(int id) throws SQLException, ClassNotFoundException {
		con = getConn();
		String sql = "select * from student where id=?";
		pst = con.prepareStatement(sql);
		pst.setInt(1, id);

		ResultSet rs = pst.executeQuery();
		Student stu = null;
		if(rs.next())
		{
			stu = new Student(rs.getInt(1), rs.getString(2), rs.getInt(3));
		}
		
		pst.close();
		con.close();
		return stu;
	}
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值