其他分享
首页 > 其他分享> > 原生JDBC流程

原生JDBC流程

作者:互联网

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();
}
}
}

}

}

标签:原生,JDBC,流程,resultSet,SQLException,connection,preparedStatement,catch,null
来源: https://www.cnblogs.com/yangj2280539387/p/15962785.html