上面两篇讲解了简单的JSP + Servlet的搭建和请求,那么后面我们肯定要用到数据交互,也就是操纵数据库的数据,包括对数字的增加,删除,修改,查询。我们就用简单的MySql来做例子
我们需要引入驱动包mysql-connector-java.jar,自行去网上下载,有很多。
下面我跟着代码看看怎么进行增删改查
1.打开数据库
// 驱动程序名 private String driver = "com.mysql.jdbc.Driver"; // URL指向要访问的数据库名scutcs private String url = "jdbc:mysql://127.0.0.1:3306/studentdb"; // MySQL配置时的用户名 private String user = "root"; // MySQL配置时的密码 private String password = "root"; private static Connection conn = null; /** * 打开数据连接 */ public void openDbConnect() { try { // 加载驱动程序 Class.forName(driver); // 连接数据库 if(conn == null || conn.isClosed()) { conn = DriverManager.getConnection(url, user, password); } if(!conn.isClosed()) { System.out.println("Succeeded connecting to the Database!"); } } catch(Exception ex) { System.out.println("访问数据库失败"); } }
2.增加数据
/** * 插入数据 * @param student * @throws SQLException */ public void insertStudent(Student student) throws SQLException { Statement statement = conn.createStatement(); // 要执行的SQL语句 String sql = "insert into student (studentname,age,classname) values('"
+ student.getStudentname() + " ',"
+ student.getAge() + ",'" + student.getClassname() + "')"; statement.execute(sql); }
3.删除数据
/** * 删除数据 * @param student * @throws SQLException */ public void deleteStudent(int id) throws SQLException { Statement statement = conn.createStatement(); // 要执行的SQL语句 String sql = "delete from student where id = " + id; statement.execute(sql); }
4.更新数据
/** * 修改数据 * @param student * @throws SQLException */ public void updateStudent(Student student) throws SQLException { Statement statement = conn.createStatement(); // 要执行的SQL语句 String sql = "update student set "; // 学生名称 if(student.getStudentname() != null && !student.getStudentname().trim().equals("") ) { sql += " studentname = '" + student.getStudentname() + "',"; } // 年龄 if(student.getAge() != 0 ) { sql += " age = " + student.getAge() + ","; } // 年级 if(student.getClassname() != null && !student.getClassname().trim().equals("") ) { sql += " classname = '" + student.getClassname() + "',"; } sql = sql.substring(0, sql.length() - 1); sql = sql + " where id = " + student.getId(); statement.execute(sql); }
5.查询数据
/** * 修改数据 * @param student * @throws SQLException */ public void queryStudent(String studentname) throws SQLException { Statement statement = conn.createStatement(); // 要执行的SQL语句 String sql = "select * from student where studentname = '" + studentname + "'"; ResultSet rs = statement.executeQuery(sql); while(rs.next()) { // 选择sname这列数据 String studentnamers = rs.getString("studentname"); String agers = rs.getString("age"); String classnamers = rs.getString("classname"); // 输出结果 System.out.println("学生名称:" + studentnamers + ",年龄:" + agers + ",班级:" + classnamers); } }
以上介绍了JAVA访问Mysql的简单代码,比较深入的后面我们再讲解。本篇文章只是带大家简单入门
结语
- 受益,学会了如何用JAVA访问Mysql数据库
本站文章为 宝宝巴士 SD.Team 原创,转载务必在明显处注明:(作者官方网站: 宝宝巴士 )
转载自【宝宝巴士SuperDo团队】 原文链接: http://www.cnblogs.com/superdo/p/4561918.html