学习记录:复习

JDBC简单链接数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**    关闭资源用		*/
Connection conn = null;
Statement stmt = null;
ResultSet rest = null;
/** 设置url,user,password,sql */
String url = "jdbc:mysql://localhost:3306/kevin?useUnicode=true&characterEncoding=utf-8";
String user = "root";
String password = "123456";
String sql = "select * from blog";
try
{
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 获得数据库链接
conn = DriverManager.getConnection(url, user, password);
// 获得Statement
stmt = conn.createStatement();
rest = stmt.executeQuery(sql);
while (rest.next())
{
System.out.println(rest.getString("title") + "_" + rest.getString("viceTitle"));
}
} catch (Exception e)
{
System.err.println("发生异常:"+e);
} finally
{//关闭资源
rest.close();
stmt.close();
conn.close();
}

关闭资源放在finally中

需引入mysql-connector-java-***.jar,如果没有使用maven可在官网下载我的网盘