public class TestJDBC {
public static void main(String[] args) throws ClassNotFoundException, sqlException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 加载数据库驱动
Class.forName("com.MysqL.jdbc.Driver");
// 通过驱动获取连接---三个参数分别是 URL Username password
connection = DriverManager.getConnection("jdbc:MysqL://localhost:3306/testmybatis", "root", "root");
// sql语句
String sql = "select * from user where username = ?";
// 获取预处理statement
preparedStatement = connection.prepareStatement(sql);
// 给属性赋值
preparedStatement.setString(1, "小花");
// 向数据库发出sql执行查询,查询出结果集
resultSet = preparedStatement.executeQuery();
// 遍历查询结果集
while (resultSet.next()) {
System.out.println(resultSet.getString("id") + " " + resultSet.getString("username"));
}
} catch (Exception e) {
e.printstacktrace();
} finally {
// 依次关闭流
if (resultSet != null) {
try {
resultSet.close();
} catch (sqlException e) {
e.printstacktrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (sqlException e) {
e.printstacktrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (sqlException e) {
e.printstacktrace();
}
}
}
}
}