JDBC

java连接数据库

需要jar包支持

  • java.sql
  • javax.sql
  • mysql-conneter-java… 连接驱动(必须导入)
  1. <!--配置连接数据库的基本信息-->
  2. String url = "jdbc:mysql://localhost:3306/mytest"
  3. String username = "root"
  4. String password = "123456"

JDBC固定六步骤

加载驱动

  1. Class.forname("com.mysql.jdbc.Driver");

连接数据库

  1. Connection connection = DriverMannger.getConnection(url,username,password);

向数据库发送SQL的对象Statement:CRUD

  1. Statement statement = connection.creatStatement();

编写SQL

  1. String sql = "select * from user";

执行SQL

  1. ResultSet rs = statement.executeQuery(sql);
  2. while(rs.next()){
  3. System.out.println("id=" + rs.getObject("id"));
  4. System.out.println("name=" + rs.getObject("name"));
  5. System.out.println("password=" + rs.getObject("password"));
  6. }

关闭连接

  1. rs.close();
  2. statement.close();
  3. connection.close;