本文通过配置文件的方式链接数据库
    image.png

    1. package com.tan;
    2. import com.mysql.jdbc.Driver;
    3. import java.io.IOException;
    4. import java.io.InputStream;
    5. import java.sql.*;
    6. import java.util.Properties;
    7. //JDBC程序示例
    8. public class JDBC_test {
    9. public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
    10. //1.加载配置文件
    11. InputStream inputStream = JDBC_test.class.getClassLoader().getResourceAsStream("jdbc.properties");
    12. Properties properties=new Properties();
    13. properties.load(inputStream);
    14. //2.读取配置文件
    15. String url = properties.getProperty("url");
    16. String username = properties.getProperty("username");
    17. String password = properties.getProperty("password");
    18. String driverClassName = properties.getProperty("driverClassName");
    19. //3.加载驱动
    20. Class.forName(driverClassName);
    21. //4.连接数据库,创建数据库对象
    22. Connection connection= DriverManager.getConnection(url,username,password);
    23. //5.执行SQL的对象
    24. Statement statement=connection.createSatement();
    25. //6.用执行SQL的对象来执行SQL
    26. String sql = "SELECT * FROM orders";
    27. ResultSet resultSet=statement.executeQuery(sql);//executeQuery是执行查询语句,还可以执行增删改查语句
    28. //返回的结果是一个链表
    29. while (resultSet.next()){
    30. System.out.println("order_num"+resultSet.getObject("order_num"));
    31. System.out.println("order_date"+resultSet.getObject("order_date"));
    32. System.out.println("cust_id"+resultSet.getObject("cust_id"));
    33. }
    34. //7.释放链接
    35. resultSet.close();
    36. statement.close();
    37. connection.close();
    38. }
    39. }

    image.png
    image.png