package DButls; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.List; public class JDBCTest { public <T> List<T> query(Class<T> clazz, String sql){ return null; } /* resultset 是封裝JDBC的結果集 1.調用 statement 的對象executeQuery 就能夠獲得結果集 ResultSet 返回的實際上就是一張數據表. 有一個指針指向數據表的第同樣的前面. * 能夠調用 next() 方法檢測下一行是否有效. 如有效該方法返回 true, 且指針下移. 至關於 * Iterator 對象的 hasNext() 和 next() 方法的結合體 * 3. 當指針對位到一行時, 能夠經過調用 getXxx(index) 或 getXxx(columnName) * 獲取每一列的值. 例如: getInt(1), getString("name") * 4. ResultSet 固然也須要進行關閉. */ public void testResultset(){ //獲取ID是4的student Connection connection = null;//鏈接 Statement statement =null; ResultSet resultSet = null; try{ //1 獲取數據庫鏈接 connection = JDBCTools.getConnection(); System.out.println(connection); //2.獲取statement statement = connection.createStatement(); System.out.println(statement); //3準備mysql String sql = "SELECT * FROM STUDENTS"; resultSet = statement.executeQuery(sql); System.out.println(resultSet); //處理返回的結果集 while (resultSet.next()){ int id = resultSet.getInt(1); String name = resultSet.getString("name"); String age = resultSet.getString("age"); System.out.print("id = "+id); System.out.print("name = "+name); System.out.println("age = "+age); } }catch (Exception e){ e.printStackTrace(); }finally { JDBCTools.release(resultSet, statement, connection); } } /* 執行插入 修改 刪除 */ public void TestInsert()throws Exception{ Connection connection = null; Statement statement = null; try{ String sql = "INSERT INTO students(NAME,age)VALUES(\"bbbb\",\"57\")"; connection = JDBCTools.getConnection(); statement = connection.createStatement(); statement.executeUpdate(sql); }catch (Exception e){ e.printStackTrace(); }finally { JDBCTools.release(statement, connection); } } //刪除數據庫 public void TesTdelect(){ Connection connection = null; Statement statement = null; try{ String sql="DELETE FROM students WHERE id > 3"; connection = JDBCTools.getConnection(); statement = connection.createStatement(); statement.executeUpdate(sql); }catch (Exception e){ e.printStackTrace(); }finally { JDBCTools.release(statement, connection); } } //嘗試修改數據 public void TestUpdate() throws Exception{ Connection connection = null; Statement statement = null; try { String sql = "UPDATE students SET age = '200' where name = 'zhangsan' "; connection = JDBCTools.getConnection(); statement = connection.createStatement(); statement.executeUpdate(sql); }catch (Exception e){ e.printStackTrace(); }finally { JDBCTools.release(statement, connection); } } }