JDBC
java连接数据库
需要jar包支持
- java.sql
- javax.sql
- mysql-conneter-java… 连接驱动(必须导入)
<!--配置连接数据库的基本信息-->
String url = "jdbc:mysql://localhost:3306/mytest"
String username = "root"
String password = "123456"
JDBC固定六步骤
加载驱动
Class.forname("com.mysql.jdbc.Driver");
连接数据库
Connection connection = DriverMannger.getConnection(url,username,password);
向数据库发送SQL的对象Statement:CRUD
Statement statement = connection.creatStatement();
编写SQL
String sql = "select * from user";
执行SQL
ResultSet rs = statement.executeQuery(sql);
while(rs.next()){
System.out.println("id=" + rs.getObject("id"));
System.out.println("name=" + rs.getObject("name"));
System.out.println("password=" + rs.getObject("password"));
}
关闭连接
rs.close();
statement.close();
connection.close;