JDBC访问数据库

一.准备条件
  1. 外界条件
  • 在数据库中首先创建表空间
  • 在创建的表中添加数据
  1. 代码部分
  • 导入数据库的驱动包(jar)
  • 加载数据库驱动
  • 获取数据库连接
  • 编写sql语句
  • 利用prepareStatement进行预处理
  • 设置参数,参数1代表第几个参数(从1开始),参数2代表参数的值
  • 向数据库发出sql语句进行查询,executeQuery(),查询到结果集resultSet
  • 遍历结果集
  • 释放资源(connection,resultSet,prepareStatement)
  1. PrepareStatement的好处
  • 达到预处理的目的,提高效率(由于我们编写代码时,每编写一句就会进行编译,效率变低,如果使用了prepareStatement预处理,这样,如果我们编写到之前出现过的相同的sql语句,就可以不用进行编译了,这样效率就可以提高了)
  1. 源码
  2. public static void main(String[] args) {
  3. //声明链接
  4. Connection connection=null;
  5. //预处理
  6. PreparedStatement preparedStatement=null;
  7. //获取的结果集
  8. ResultSet resultSet=null;
  9. //加载驱动
  10. try {
  11. Class.forName("com.mysql.jdbc.Driver");
  12. //获取链接
  13. connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "123456");
  14. //创建sql语句
  15. String sql="select * from user where username= ? ";
  16. //预处理 
  17. preparedStatement = connection.prepareStatement(sql);
  18. preparedStatement.setString(1, "王五");
  19. resultSet = preparedStatement.executeQuery();
  20. while(resultSet.next()){
  21. System.out.println(resultSet.getString("id")+resultSet.getString("username"));
  22. }
  23. } catch (Exception e) {
  24. // TODO Auto-generated catch block
  25. e.printStackTrace();
  26. }finally{
  27. //释放资源
  28. if(resultSet!=null){
  29. try {
  30. resultSet.close();
  31. } catch (Exception e2) {
  32. // TODO: handle exception
  33. }
  34. }if(connection!=null){
  35. try {
  36. connection.close();
  37. } catch (Exception e2) {
  38. // TODO: handle exception
  39. }
  40. }if(preparedStatement!=null){
  41. try {
  42. preparedStatement.close();
  43. } catch (Exception e2) {
  44. // TODO: handle exception
  45. }
  46. }
  47. }
  48. }
原文地址:https://www.cnblogs.com/itcx1213/p/6337637.html