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 List query(Class 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);
}
}
}