package top.simba1949;
import com.mysql.jdbc.Driver;
import org.junit.Test;
import java.sql.*;
/**
* @author SIMBA1949
* @date 2019/8/24 17:21
*/
public class ApplicationTest {
/**
*
* @throws SQLException
*/
@Test
public void jdbcTest() throws SQLException {
// 注册驱动
DriverManager.deregisterDriver(new Driver());
// 获取连接
String url = "jdbc:mysql://127.0.0.1:3306/db_sql_learn?serverTimezone=Asia/Shanghai";
String username = "root";
String password = "19491001";
Connection connection = DriverManager.getConnection(url, username, password);
// 获取可执行的 SQL 语句对象
Statement statement = connection.createStatement();
String sql = "select * from student";
statement.execute(sql);
// 处理结果
ResultSet resultSet = statement.getResultSet();
while (resultSet.next()){
// getXXX(int column) :根据每一行数据获取对应列的值,从 1 开始
System.out.print(resultSet.getObject(1) + " | ");
System.out.print(resultSet.getObject(2) + " | ");
System.out.print(resultSet.getObject(3) + " | ");
System.out.println(resultSet.getObject(4) + " | ");
}
// 释放资源
resultSet.close();
statement.close();
connection.close();
}
/**
* 预编译
* @throws SQLException
*/
@Test
public void jdbcPrepareTest() throws SQLException {
// 注册驱动
DriverManager.deregisterDriver(new Driver());
// 获取连接
String url = "jdbc:mysql://127.0.0.1:3306/db_sql_learn?serverTimezone=Asia/Shanghai";
String username = "root";
String password = "19491001";
Connection connection = DriverManager.getConnection(url, username, password);
// 获取可执行的 SQL 语句对象, 预编译对象
String sql = "select * from student where id > ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 设置占位符的值
preparedStatement.setInt(1, 41);
preparedStatement.executeQuery();
// 处理结果
ResultSet resultSet = preparedStatement.getResultSet();
while (resultSet.next()){
// getXXX(int column) :根据每一行数据获取对应列的值,从 1 开始
System.out.print(resultSet.getObject(1) + " | ");
System.out.print(resultSet.getObject(2) + " | ");
System.out.print(resultSet.getObject(3) + " | ");
System.out.println(resultSet.getObject(4) + " | ");
}
// 释放资源
resultSet.close();
preparedStatement.close();
connection.close();
}
}