1:加載驅(qū)動(dòng)
2:獲取數(shù)據(jù)庫(kù)鏈接
3:獲取發(fā)送數(shù)據(jù)庫(kù)鏈接
4:發(fā)送sql語(yǔ)句獲取結(jié)果
5:處理結(jié)果
6:關(guān)閉資源
1:加載驅(qū)動(dòng)
Class.forName("com.mysql.cj.jdbc.Driver");
2.獲取數(shù)據(jù)庫(kù)鏈接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/wanan", "root", "123456");
3.獲取發(fā)送sql語(yǔ)句的工具
statement=connection.createStatement();
4.發(fā)送sql語(yǔ)句獲取結(jié)果
String sql="select * from student";
resultSet = statement.executeQuery(sql);
5.處理結(jié)果
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.釋放資源(先開(kāi)后閉)
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.注冊(cè)驅(qū)動(dòng)
Class.forName("com.mysql.cj.jdbc.Driver");
//2.獲取數(shù)據(jù)庫(kù)鏈接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/wanan", "root", "123456");
//3.獲取發(fā)送sql語(yǔ)句的工具
statement=connection.createStatement();
//4.發(fā)送sql語(yǔ)句獲取結(jié)果
String sql="select * from student";
resultSet = statement.executeQuery(sql);
//5.處理結(jié)果
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.釋放資源(先開(kāi)后閉)
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}