JDBC statment连接数据库

public class jdbcFirstDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.用户身份和url
String url="jdbc:mysql://localhost:3306/jdbcstudy?serverTimezone=GMT%2B8";
String username = "root";
String password = "123456789";
  //2.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");//固定写法
    //3.连接成功,数据库对象  Connection 代表数据库
Connection connection = DriverManager.getConnection(url,username,password);

//4.执行SQL的对象 Statment 执行Sql的对象
Statement statement = connection.createStatement();
//5.执行SQL的对象 去 执行SQL,可能存在结果 查看返回结果
String sql = "SELECT * FROM users";

ResultSet resultSet = statement.executeQuery(sql);//返回结果集 封装了查询的结果

while ((resultSet.next())){
System.out.println("id=" + resultSet.getInt("id"));
System.out.println("name=" + resultSet.getString("name"));
System.out.println("pwd=" + resultSet.getString("password"));
System.out.println("email=" + resultSet.getString("email"));
System.out.println("birth=" + resultSet.getDate("birthday"));
System.out.println("-----------------------------");
}
//6.释放连接
resultSet.close();
statement.close();
connection.close();
}
}
//工具类
posted @ 2022-10-14 16:13  西东怪  阅读(14)  评论(0编辑  收藏  举报
返回顶端