开发者学堂课程【JDBC数据开发入门:什么是JDBC】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/29
JDBC之代码规范化
一、规范化代码含义
所谓规范化代码就是无论是否出现异常,都要关闭Rsultset、Statement,以及Connection
//规范化
public void fun3 ( )throws Exception {
connection con = null;//定义引用
statement stmt = null;
Resultset rs = null;
try {
/*
—、得到连接*/
string driverclassName = "com.mysql.jdbc.Driver";
string url = "jdbc:mysql : / / localhost : 3306/exam" ;
string username = "root";
string password = "123";
class .forName(driverclassName) ;
connection con = DriverManager.getConnection(url,username,password) ;
catch (Exception e) {
}finally {
//关闭
一、创建Statement*/
Stmt=con.createStatement();
string sql = "select * from emp";
ResultSet rs =stmt-executeQuery (sql);
/*
二、循环遍历rs,打印其中数据
*getstring()和getobject ()是通用的!
*/
While(rs.next()) {
System.out.println(rs.getobject(1)+ “,” +rs.getstring(ename));+”,”+rs.getDouble(“sal”));
} catch(Exception e) {
} finally {
// 关闭
If(rs !=null) rs.close();
If(Stmt !=null) stmt.close();
If(con !=null) con.close();
}