使用jdbc连接数据库
之前学习网上视频教程的时候,使用过jdbc连接数据库。不过是照着他的代码打的,记忆不够深刻。
现在只看官方文档,重新做了一遍。
0.前期准备:
IDE:eclipse
JAR:mysql-connector-java-5.1.46.jar
新建一个java web项目,将jdbc的jar包添加到项目中。
1.加载Driver
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("load mysql driver success!");
} catch (ClassNotFoundException e) {
System.out.println("load mysql driver failed");
e.printStackTrace();
}
2.连接Database
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/pca", "root", "123456");
System.out.println("connect mysql success!");
} catch (SQLException e) {
System.out.println("connect mysql failed");
e.printStackTrace();
}
3.执行Statement
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
// rs = stmt.executeQuery("select * from provinces")
if (stmt.execute("select * from provinces")) {
rs = stmt.getResultSet();
while (rs.next()) {
System.out.println(rs.getInt("ID")
+ rs.getString("province")
+ rs.getInt("provinceId"));
}
}
} catch (SQLException e) {
System.out.println("failed to execute the sql statement");
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {}
stmt = null;
}
}
4.几个Tips
1.在Step 3中,try–catch–finally 语句块,借用mysql document中的一段话
It is a good idea to release resources in finally{} block in any reverse order of their creation if they are no longer needed.
2.没用用到PrepareStatement,将在下次好好Illustrate一下
5.Conclusion
终于自己照着官网做了一遍,妈妈再也不用担心我用百度知道了
成就感嘛,肯定会有啦!