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;
}
}database class
最新推荐文章于 2021-04-11 04:48:37 发布
本文提供了一个使用 Java 进行 MySQL 数据库操作的示例代码,包括连接数据库、添加、删除、更新学生信息及查询所有学生记录的功能实现。
1287

被折叠的 条评论
为什么被折叠?



