java开发JDBC连接数据库

来源:互联网 发布:json和ajax区别 编辑:程序博客网 时间:2024/06/05 17:51

步骤:加,连,语,执,释,

public List<Student> list() {

List<Student> list =new ArrayList<>();

String sql ="SELECT * FROM student";

Connection conn  =null;

    Statement st = null;

ResultSet rs = null;

try {

//1.加载注册驱动

Class.forName("com.mysql.jdbc.Driver");

//2.获取连接对象  

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&user=root&password=123456");

System.out.println("数据库连接成功!");

//3.创建语句对象

stconn.createStatement();

//4.执行sql

  rs =st.executeQuery(sql);

  while (rs.next()) {

  long id = rs.getLong("id");

  String name = rs.getString("name");

  Integer age = rs.getInt("age");

 //封装到domian组件中

  Student stu = new Student(id,name,age);

 //把对象包装到list中

  list.add(stu);

}

System.out.println(list);

returnlist;

} catch (Exceptione) {

thrownew RuntimeException(e);

}finally {

//5.关闭资源

try {

if (rs !=null) {

rs.close();

}

} catch (Exceptione) {

e.printStackTrace();

thrownew RuntimeException(e);

}finally {

try {

if (st !=null) {

st.close();

}

} catch (Exception e) {

thrownew RuntimeException(e);

}finally {

try {

if (conn !=null) {

conn.close();

}

} catch (Exception e) {

thrownew RuntimeException(e);

}finally {

}

}

}

}

}

}


0 0