public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
String url = "jdbc:mysql://localhost:3306/new_schema?useSSL=false";
String userName = "root";
String passWord = "123456";
ResultSet rs = null;
List<User> list = new ArrayList<User>();
try {
//反射驱动 加载mysql的驱动类
Class.forName("com.mysql.jdbc.Driver");
//获得数据库的连接
connection = DriverManager.getConnection(url, userName, passWord);
//创建statement 传输sql语句 执行sql语句 返回结果集
statement = connection.createStatement();
//mysql 查询语句
String sql = "select * from user_mes";
rs = statement.executeQuery(sql);
while(rs.next()) {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
list.add(user);
// int id = rs.getInt("id");
// String name = rs.getString("name");
// int age = rs.getInt("age");
// System.out.println("ID:"+id+"name:"+name+"Age"+age);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
try {
if (rs != null) {
rs.close();
}
if(statement != null) {
statement.close();
}
if(connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
System.out.println(list.size());
像这种连接数据库的文件,我们一般不会写成类,一般都会写在配置文件里面
读写文件必须是绝对路径,相对路径是读不到文件的