import java.sql.*;
public class Test {
public static void main(String[] args) {
Connection con = null;
Statement sta = null;
ResultSet res = null;
try {
/* <!--加载驱动类--> */
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String passwd = "root";
/* <!--通过大管家拿到与指定数据库连接的接口Connection的一个对象--> */
con = DriverManager.getConnection(url,user,passwd); //ClassNotFoundException
/* <!--通过接口con中的特定方法拿到sql语句对象--> */
String sql = "select * from login";
sta = con.createStatement();
/* <!--将结果集返回给ResultSet对象--> */
res = sta.executeQuery(sql);
while(res.next()){
System.out.println(res.getString("username")); //username 为数据库里面的字段名
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
try{
if(res!=null){ <!--finally 后面的代码是一定会执行的,用finally的好处就是当在增删改查阶段产生了异常,导致程序无法往下走,那么你
建立的 con、res、sta连接就无法关闭了,那么当你的程序启动多次以后,你的内存就会不知不觉的被全部占用了。
这时候finally的特点就是,无论try还是catch里面产生什么样的异常都会义无反顾走finally,从而内存不会被浪费-->
res.close();
res = null; //关闭之后将空间回收
}
if(sta!=null){
sta.close();
sta = null;
}
if(con!=null){
con.close();
con = null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}