java 操作数据库通用类
最近学习java,连接sql server 2008成功了,能够写入数据,读取数据,但是每次都要填写帐号,和密码,很烦人,求操作数据库通用类--------------------编程问答-------------------- ? Java操作数据库最简单了,JDBC,JDO,JPA啥的,一把一把的。 --------------------编程问答--------------------
--------------------编程问答--------------------
/**
* database DEFAULT CHARACTER SET utf8
*
*/
public class JdbcUtil {
private static final String url = "jdbc:mysql://localhost:3306/dbdemo?useUnicode=true&characterEncoding=UTF-8";
private static final String user = "root";
private static final String password = "sa";
private static ThreadLocal<Connection> connectionContainer = new ThreadLocal<Connection>();
/**
* 注册
*
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection register() {
Connection connection = connectionContainer.get();
try {
if (connection == null) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection = DriverManager.getConnection(url, user, password);
}
connectionContainer.set(connection);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
public static void freeResource(Statement statement, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
Connection connection = connectionContainer.get();
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
connectionContainer.remove();
}
}
}
你这个是得到数据库连接的对象吗? --------------------编程问答-------------------- 把数据库连接单独写成一个单例类,账号和密码写进去 --------------------编程问答--------------------
我现在已经这样做了,如何用数据库的事物,存储过程等,谁有封装好的通用类,请分享一下,谢谢 --------------------编程问答-------------------- 你是想以对象的形势来操作数据库?引入Hibernate就解决了啊 --------------------编程问答--------------------
那就直接上hibernate把 --------------------编程问答-------------------- 不一定要用hibernate,spring jdbc也可以,思想就是spring aop切入,事务支持,连接池获取连接。在切入点之前开启事务,执行完事务提交
补充:Java , Java SE