资源描述:
《JAVA实习报告_9》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实验九通过JDBC方式操作数据库1.实验目的(1)掌握通过JDBC方式操作数据库的基本步骤。(2)掌握增、删、改记录的方法。(3)掌握查询记录以及遍历查询结果的方法。2.实验内容实验题1学生信息管理函数。数据库中的信息参考Exp9.1.txt,这些命令用来创建student表,包含学生的学号、姓名、年龄信息。①根据学号,可以查询到学生的姓名和年龄;②给定学生的学号、姓名、年龄,在表中追加一行信息;③给定学生的学号,可以从表中删除该学生的信息;[基本要求]对上面的每一个功能编写相应的函数,并测试。具体实现代码如下:importjava.sql.*;i
2、mportjavax.swing.JOptionPane;publicclasstest1implementsDataBase{static{try{Class.forName(Driver);System.out.println("数据库连接成功");}catch(ClassNotFoundExceptione){e.printStackTrace();System.out.println("建立数据库发生错误!");}}publicvoidadd(StringS1,StringS2,intS3){try{Connectionconn=Drive
3、rManager.getConnection(URL,USERNAME,PASSWORD);StringSQL="insertintostudent(stu_num,stu_name,Stu_age)values(?,?,?)";PreparedStatementPS=(PreparedStatement)conn.prepareStatement(SQL);PS.setString(1,S1);PS.setString(2,S2);PS.setInt(3,S3);PS.executeUpdate();PS.close();conn.close()
4、;JOptionPane.showMessageDialog(null,"提示"+""+"添加成功");}catch(SQLExceptione){JOptionPane.showMessageDialog(null,"提示"+""+"插入失败!");}}publicvoidchange(StringS1,intS2,StringS3){try{Connectionconn=DriverManager.getConnection(URL,USERNAME,PASSWORD);StringSQL1="updatestudentsetS
5、tu_name=?whereStu_num=?";PreparedStatementPS1=conn.prepareStatement(SQL1);PS1.setString(1,S1);PS1.setString(2,S3);PS1.executeUpdate();PS1.close();StringSQL2="updatestudentsetStu_age=?whereStu_num=?";PreparedStatementPS2=(PreparedStatement)conn.prepareStatement(SQL2);PS2.setInt
6、(1,S2);PS2.setString(2,S3);PS2.executeUpdate();PS2.close();conn.close();JOptionPane.showMessageDialog(null,"提示"+""+"修改成功");}catch(SQLExceptione){JOptionPane.showMessageDialog(null,"提示"+""+"更新失败!");}}publicvoiddelete(StringS){try{Connectionconn=DriverManager.getConnecti
7、on(URL,USERNAME,PASSWORD);StringSQL1="deletefromstudentwhereStu_num=?";PreparedStatementPS1=conn.prepareStatement(SQL1);PS1.setString(1,S);PS1.executeUpdate();PS1.close();conn.close();JOptionPane.showMessageDialog(null,"提示"+""+"删除成功");}catch(SQLExceptione){JOptionPane.show
8、MessageDialog(null,"提示"+""+"删除失败");}}publicvoidfind(){try