JDBC
准备一个jdbc配置文件
XXX.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/student?useSSL=false&allowPublicKeyRetrieval=true
root=root
password=123456
java文件写法
编写jdbc共分六大步骤
- 注册驱动
- 连接数据库
- 获取数据库操作对象
- 执行sql语句
- 处理查询结果集(Select)
- 关闭连接对象
Properties properties = new Properties();
FileInputStream inputStream = new FileInputStream(Thread.currentThread().getContextClassLoader().getResource("properties.properties").getPath());
properties.load(inputStream);
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String root = properties.getProperty("root");
String password = properties.getProperty("password");
//注册驱动
Class.forName(driver);
//连接数据库
Connection con = DriverManager.getConnection(url,root,password);
//获取数据库操作对象
PreparedStatement preparedStatement = con.prepareStatement("SELECT * from t_student where sex=?");
preparedStatement.setString(1,"man");
//执行sql语句
ResultSet resultSet = preparedStatement.executeQuery();
//处理查询结果集
while(resultSet.next()){
System.out.println(" "+resultSet.getString("Name")+" | "+resultSet.getInt("age")+" | "+resultSet.getString("sex"));
}
//关闭链接
resultSet.close();
preparedStatement.close();
con.close();