mysqldbutil.java

来自「这是我在东方标准学习的时候做的一个项目」· Java 代码 · 共 101 行

JAVA
101
字号
package dao.product.mysql;

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

import common.Constant;
import dao.product.DbUtil;

public class MySQLDbUtil extends DbUtil{

	private static final String MYSQL_URL = "jdbc:mysql://localhost/mysql";// use mysql

	private static final String MYSQL_NAME = "root";

	private static final String MYSQL_PASSWORD = "tiger";

	private static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";

	private Connection conn = null;

	private Statement stat = null;

	public MySQLDbUtil() {
		try {
			Class.forName(MYSQL_DRIVER);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Connection getConnection() {
		try {
			if (conn == null || conn.isClosed()) {
				conn = DriverManager.getConnection(MYSQL_URL, MYSQL_NAME, MYSQL_PASSWORD);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public int executeUpdate(String sql) {
		try {
			conn = this.getConnection();
			stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			stat.executeUpdate(sql);
			return Constant.OK;
		} catch (Exception e) {
			e.printStackTrace();
			return Constant.ERROR;
		}
	}

	public ResultSet executeQuery(String sql) {
		try {
			conn = this.getConnection();
			stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			return stat.executeQuery(sql);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public int close() {
		// try {
		// stat.close();
		// } catch (Exception e) {
		// e.printStackTrace();
		// return Constant.ERROR;
		// }
		if (conn == null) {
			return Constant.ERROR;
		}
		try {
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
			return Constant.ERROR;
		}
		return Constant.OK;

	}

	public void closeConnection(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}

⌨️ 快捷键说明

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