1:加载驱动
2:获取数据库链接
3:获取发送数据库链接
4:发送sql语句获取结果
5:处理结果
6:关闭资源
1:加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
2.获取数据库链接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/wanan", "root", "123456");
3.获取发送sql语句的工具
statement=connection.createStatement();
4.发送sql语句获取结果
String sql="select * from student";
resultSet = statement.executeQuery(sql);
5.处理结果
while (resultSet.next()){
int sid = resultSet.getInt("sid");
String sname = resultSet.getString("sname");
String sex=resultSet.getString("sex");
int age=resultSet.getInt("age");
String phone=resultSet.getString("phone");
System.out.println("sid:"+sid+"--sname:"+sname+"--sex:"+sex+"--age:"+age+"--phone"+phone);
}
6.释放资源(先开后闭)
resultSet.close();
statement.close();
connection.close();
7:全部代码
public class Servlt {
public static void main(String[] args) {
Connection connection=null;
Statement statement=null;
ResultSet resultSet=null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取数据库链接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/wanan", "root", "123456");
//3.获取发送sql语句的工具
statement=connection.createStatement();
//4.发送sql语句获取结果
String sql="select * from student";
resultSet = statement.executeQuery(sql);
//5.处理结果
while (resultSet.next()){
int sid = resultSet.getInt("sid");
String sname = resultSet.getString("sname");
String sex=resultSet.getString("sex");
int age=resultSet.getInt("age");
String phone=resultSet.getString("phone");
System.out.println("sid:"+sid+"--sname:"+sname+"--sex:"+sex+"--age:"+age+"--phone"+phone);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
try {
//6.释放资源(先开后闭)
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}