这时是数据库的表:
DROP DATABASE IF EXISTS `hibernate`;
CREATE DATABASE `hibernate` ;
USE `hibernate`;
CREATE TABLE `person` (
`id` int(32) NOT NULL DEFAULT '0',
`name` varchar(20) NOT NULL,
`password` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
1.首先我们先做一个接口,现在先不管它,等下你就知道他有什么用啦
package com.dongguoh;
import java.sql.*;
public interface IStatementCallback {
public Object doInStatement(Statement stmt) throws RuntimeException,SQLException;
}
2.而这里是最关键的,就是建一个Jdbc的模板方法,把那些经常要做的try{} catch{}都写在一个类里
免得以后每次都还去写。这就成啦代码复用.
package com.dongguoh;
import java.sql.*;
public class JdbcTemplate {
public Object execute(IStatementCallback action) {
Connection conn = null;
Statement stmt = null;
Object result = null;
try {
conn=this.getConnection();
conn.setAutoCommit(false);
stmt=conn.createStatement();
result=action.doInStatement(stmt);
conn.commit();
conn.setAutoCommit(true);
} catch (SQLException e) {
transactionRollback(conn);
e.printStackTrace();
throw new RuntimeException(e);
}finally{
this.closeStatement(stmt);
this.closeConnection(conn);
}
return result;
}
private void transactionRollback(Connection conn){
if(conn!=null){
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private void closeStatement(Statement stmt){
if(stmt!=null){
try {
stmt.close();
stmt=null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private void closeConnection(Connection conn){
if(conn!=null){
try {
conn.close();
conn=null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private Connection getConnection() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1/Hibernate";
Connection conn=null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, "root", "dongguoh");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
下面是我们的测试方法:
package com.dongguoh;
import java.sql.*;
import junit.framework.TestCase;
public class TestTemplate extends TestCase {
public void testJdbcTemplate(){
JdbcTemplate jt=new JdbcTemplate();
int count=(Integer)jt.execute(new IStatementCallback(){
public Object doInStatement(Statement stmt) throws RuntimeException, SQLException {
String sql="INSERT INTO person VALUES(1,'dongguoh','123456')";
int result=stmt.executeUpdate(sql);
return new Integer(result);
}
});
System.out.println("Count: "+count);
jt.execute(new IStatementCallback(){
public Object doInStatement(Statement stmt) throws RuntimeException, SQLException {
String sql="SELECT name,password FROM person WHERE id=1";
ResultSet rs=null;
rs=stmt.executeQuery(sql);
if(rs.next()){
System.out.println(rs.getString("name"));
System.out.println(rs.getString("password"));
}
return new Integer(1);
}
});
}
}
测试结果:
Count: 1
dongguoh
123456
如果你要用 PreparedStatement 的话,想传参数的话,再写一个接口来实现,再在JdbcTemplate重载一个方法
如public Object execute(IPreparedStatementCallback action,,Object[] objArray)再多传一个你要传递的参数数组,
评论排行榜