JdbcResultSet
package jdbc;
import org.junit.Test;
import java.lang.reflect.Field;
import java.sql.*;
public class QueryResultSetTest {
@Test
public void queryTest1() {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = JdbcUtils.getConnection();
String sql = "SELECT `id`,`username`,`password`,`email` FROM t_user WHERE id = ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1, 1);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
int id = resultSet.getInt(1);
String username = resultSet.getString(2);
String password = resultSet.getString(3);
String email = resultSet.getString(4);
User user = new User(id, username, password, email);
System.out.println(user);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils.close(connection, preparedStatement, resultSet);
}
}
public User query(String sql, Object... args) {
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
connection = JdbcUtils.getConnection();
ps = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
if (rs.next()) {
User user = new User();
for (int i = 0; i < columnCount; i++) {
Object value = rs.getObject(i + 1);
String columnName = metaData.getColumnName(i + 1);
Field field = User.class.getDeclaredField(columnName);
field.setAccessible(true);
field.set(user, value);
}
return user;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.close(connection, ps, rs);
}
return null;
}
@Test
public void test(){
String sql = "SELECT `id`,`username`,`password`,`email` FROM t_user WHERE id = ?";
System.out.println(query(sql, 2));
}
}