標籤:
上面兩篇講解了簡單的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的簡單代碼,比較深入的後面我們再講解。本篇文章只是帶大家簡單入門
結語
本站文章為 寶寶巴士 SD.Team 原創,轉載務必在明顯處註明:(作者官方網站: 寶寶巴士 )
轉載自【寶寶巴士SuperDo團隊】 原文連結: http://www.cnblogs.com/superdo/p/4561918.html
[JavaWeb基礎] 003.JAVA訪問Mysql資料庫