JDBC查询类如下
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Query {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/usa", "root", "root");
statement = connection.createStatement();
rs = statement.executeQuery("select * from student");
while (rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
System.out.println(id + name);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
每次这样查询很麻烦而且该类本身“变量”只是sql语句,因此我们将其封装为查询方法,传入sql语句作为参数
package newjdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
interface IRowMapper{
void rowMapper(ResultSet resultSet);
}
public class Select {
public static void select(String sql,IRowMapper rowMapper) {//2.上转型对象
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.jdbc.Driver");//3.加载驱动类
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/usa", "root", "root");//4.创建连接
statement = connection.createStatement();//5.创建语句
resultSet = statement.executeQuery(sql);//6.执行语句
rowMapper.rowMapper(resultSet);
//7.处理结果,rowMapper变量存的是IRowMapper接口实现类RowMapper对象地址,因此这里调用重写后的方法
} catch (Exception e) {
e.printStackTrace();
} finally {//8.释放资源
if(statement!=null) {
try {
statement.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(connection!=null) {
try {
connection.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
class RowMapper implements IRowMapper{
@Override
public void rowMapper(ResultSet resultSet) {
try {
while(resultSet.next()) {//遍历结果
String id = resultSet.getString("id");
String name = resultSet.getString("name");
System.out.println(id+name);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
select("select * from student",new RowMapper());//1.传入sql语句并新建RowMapper实现类对象
}
}