Java实现对mysql数据库的增删查改
前面我们已经讲过如何实现对mysql数据库的连接。最简单的数据库操作就是增删查改。
其实对懂得实现对数据库的连接,其余的,对于一些简单的操作都是很简单的。
查看数据
public static void show_info() throws ClassNotFoundException, SQLException{ sql = "select * from stu_info"; Connection con = connect(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(sql); System.out.println("学号 姓名 出生日期 性别 课程号"); while(rs.next()){ System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4)+" "+rs.getString(5)); } con.close(); }
public static void insert() throws ClassNotFoundException, SQLException{ Connection con = connect(); System.out.println("请输入数据:"); Scanner input = new Scanner(System.in); int sID = input.nextInt(); String sName = input.next(); String brithday = input.next(); String sex = input.next(); String s_cid = input.next(); Statement st = con.createStatement(); sql = "insert into stu_info values(?,?,?,?,?)"; PreparedStatement pre = (PreparedStatement) con.prepareStatement(sql); pre.setInt(1, sID); pre.setString(2, sName); pre.setString(3, brithday); pre.setString(4, sex); pre.setString(5, s_cid); int count = pre.executeUpdate(); System.out.println(count+"条数据发生了变化"); pre.close(); con.close(); }
public static void modify() throws ClassNotFoundException, SQLException{ Connection con = connect(); Scanner input = new Scanner(System.in); System.out.println("输入修改的学号"); int sID = input.nextInt(); System.out.println("输入修改信息"); String sName = input.next(); String brithday = input.next(); String sex = input.next(); String s_cid = input.next(); sql ="update stu_info set sName = ?,birthday = ?,sex = ? ,s_cid = ? where sID = " +sID; PreparedStatement pre = (PreparedStatement) con.prepareStatement(sql); pre.setString(1, sName); pre.setString(2, brithday); pre.setString(3, sex); pre.setString(4, s_cid); int count = pre.executeUpdate(); System.out.println(count+"条数据发生变化"); pre.close(); con.close(); }
删除数据
public static void delete() throws ClassNotFoundException, SQLException{ Connection con = connect(); System.out.println("输入删除的学号"); Scanner input = new Scanner(System.in); int sID = input.nextInt(); sql = "delete from stu_info where sID = " +sID; Statement st = con.createStatement(); int count = st.executeUpdate(sql); System.out.println(count+"条数据发生了变化"); con.close(); }
这里出现了两个不同的类Statement 和PrepardStatement。其中PrepardStatement是由Statement继承过来的。
PrepardStatement提高了代码的可读性和维护性
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 用JAVA实现数据库查询
- 下一篇: Java连接MySQL数据库并查询结果