下面是个完整的范例,注意我们在查询结束后,可以使用Statement的close()方法来释放Statement的资料库资源与JDBC资源,而最后不使用连线时也使用Connection的close()来关闭连线:
DBTest.java
package onlyfun.caterpillar;
import java.sql.*;
public class DBTest ...{
public static void main(String[] args) ...{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/GUESTBOOK?" + "useUnicode=true&characterEncoding=Big5" ;
String user = "caterpillar";
String password = "123456";
Connection conn = null;
Statement stmt = null;
try ...{
Class.forName(driver);
conn = DriverManager.getConnection(URL, user, password);
stmt = conn.createStatement();
stmt.execute("INSERT INTO message VALUES(‘xxx" +
"‘, ‘xxx@mail.com‘, ‘留言吧‘, "+ "‘2007-05-15‘, ‘顶‘)");
ResultSet result = stmt.executeQuery("SELECT * FROM message");
while(result.next()) ...{
System.out.print(result.getString(1) + " ");
System.out.print(result.getString(2) + " ");
System.out.print(result.getString(3) + " ");
System.out.print(result.getString(4) + " ");
System.out.println(result.getString(5) + " ");
}
}catch(ClassNotFoundException e) ...{
System.out.println("找不到驱动程式");
e.printStackTrace();
}catch(SQLException e) ...{
e.printStackTrace();
}finally ...{
if(stmt != null) ...{
try ...{
stmt.close();
}catch(SQLException e) ...{
e.printStackTrace();
}
}
if(conn != null) ...{
try ...{
conn.close();
}catch(SQLException e) ...{
e.printStackTrace();
}
}
}
}
}
最后注意的是,Connection物件预设为自动"认可"(Commit),也就是Statement执行SQL叙述完后,马上对资料库进行操作变更,如果想要对Statement要执行的SQL进行除错,可以使用setAutoCommit(false)来将自动认可取消,在执行完SQL之后,再呼叫Connection的commit()方法认可变更,使用Connection的getAutoCommit()可以测试是否设定为自动认可.
不过无论是否有无执行commit()方法,只要SQL没有错,在关闭Statement或Connection前,都会执行认可动作,对资料库进行变更.
标签: