package jdbc_mysql.statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
public class testStatementResultSet {
@Test
public void testDQL(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/school";
String user = "root";
String password = "root";
try {
conn = DriverManager.getConnection(url, user, password);
stmt = conn.createStatement();
String sql = "select id,name,math from student";//可更改sql执行语句
rs = stmt.executeQuery(sql);
//使用ResultSet
while(rs.next()){
//通过下标取数据
int id = rs.getInt(0);
String name = rs.getString(1);
int math = rs.getInt(2);
System.out.println(id+name+math);
//通过字段名取数据
id=rs.getInt("id");
name = rs.getString("name");
math = rs.getInt("math");
System.out.println("###"+id+name+math);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rs = null;
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stmt = null;
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//conn=null;
}
}
}
}