dbhelper.java

来自「对XML和DB的CURD的基本操作.使用的两个比较常用的组合设计模式:MVC模式」· Java 代码 · 共 95 行

JAVA
95
字号
package com.mycompany.myapp.dao.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.mycompany.myapp.util.Constants;

/**
 * the database helper with some convenience methods for jdbc operations. 
 */
public class DbHelper {
	public static Connection conn;
	
	/**
	 * get the connection
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection() throws Exception {
		Class.forName(Constants.CLASS_NAME);
		conn = DriverManager.getConnection(Constants.CONNET_STR,
				Constants.USER, Constants.PASSWORD);
		return conn;
	}

	/**
	 * get the resultSet
	 * @param sql
	 * @return
	 * @throws Exception
	 */
	public static ResultSet getResultSet(String sql) throws Exception {
		boolean bSuccess = true;
		ResultSet rs = null;
		Statement stmt;
		Connection con = getConnection();
		if (con == null)
			bSuccess = false;
		if (bSuccess) {
			try {
				stmt = con.createStatement();
				rs = stmt.executeQuery(sql);
			} catch (SQLException e) {
				e.printStackTrace();
				bSuccess = false;
			}
		}
		if (bSuccess)
			return rs;
		else
			return null;
	}

	/**
	 * execute the sql
	 * @param sql
	 * @return
	 * @throws Exception
	 */
	public static boolean execute(String sql) throws Exception {
		boolean bSuccess = true;
		Statement stmt = null;
		Connection con = getConnection();
		if (con == null)
			bSuccess = false;
		if (bSuccess) {
			try {
				stmt = con.createStatement();
				bSuccess = stmt.execute(sql);
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
				bSuccess = false;
			}
		}
		return bSuccess;
	}

	/**
	 * close the connection
	 * @param conn
	 */
	public static void closeConnection() {
		try {
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?