/**
* 快速入门
*/
@Test
public void demo1() {
/**
* * 1.加载驱动.
* * 2.获得连接.
* * 3.编写sql执行sql.
* * 4.释放资源.
*/
// 1.加载驱动:
// DriverManager.registerDriver(new Driver());
// 查看源代码了 只要Driver类一加载,注册驱动.
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// 2.获得连接:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day17", "root", "123");
// 3.执行sql.
// 3.1编写一个sql语句
String sql = "select * from user";
// 3.2创建一个执行sql的对象.
stmt = conn.createStatement();
// 3.3调用stmt中的方法执行sql语句
rs = stmt.executeQuery(sql);
// 3.4遍历结果集
while(rs.next()){
int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
System.out.println(id+" "+username+" "+password);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
// 4.释放资源.
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) {
// ignore }
} rs = null;
} if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) {
// ignore }
} stmt = null;
} if (conn != null) {
try {
conn.close();
} catch (SQLException sqlEx) { // ignore } }
// 手动设置为null.
conn = null;
}
}
}