欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java链接MySQL数据库 博客分类: JavaMySQL mysqljavadatabase数据库 

程序员文章站 2024-03-05 21:56:37
...
Java链接MySQL数据库创建方式

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

public class MySQLDAO {
	private String ip = null;
	private String port = null;
	private String database = null;
	private String user = null;
	private String password = null;
	private Connection con = null;

	/**
	 * 
	 * @param ip
	 * @param port
	 * @param database
	 * @param user
	 * @param password
	 */
	public MySQLDAO(String ip, String port, String database, String user, String password) {
		this.ip = ip;
		this.port = port;
		this.database = database;
		this.user = user;
		this.password = password;
	}

	/**
	 * 
	 * @return Connection
	 */
	public Connection getMySQLConnection() {
		int time = 0;
		String url = "jdbc:mysql://" + ip + ":" + port + "/" + database + "?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull";
		try {
			for (; (++time < 3) && (con == null || con.isClosed());) {
				Class.forName("com.mysql.jdbc.Driver");
				con = DriverManager.getConnection(url, user, password);
			}
		} catch (Exception e) {
			System.err.println("Cannot get MySQL database connection.");
			e.printStackTrace();
		}
		return con;
	}

	/**
	 * 
	 * @param con
	 *            Connection
	 * @return
	 */
	public boolean closeMySQLResource(Connection con) {
		return closeMySQLResource(con, null, null);
	}

	/**
	 * 
	 * @param ps
	 *            Statement
	 * @return
	 */
	public boolean closeMySQLResource(Statement ps) {
		return closeMySQLResource(null, ps, null);
	}

	/**
	 * 
	 * @param rs
	 *            ResultSet
	 * @return
	 */
	public boolean closeMySQLResource(ResultSet rs) {
		return closeMySQLResource(null, null, rs);
	}

	/**
	 * 
	 * @param con
	 *            Connection
	 * @param ps
	 *            Statement
	 * @return
	 */
	public boolean closeMySQLResource(Connection con, Statement ps) {
		return closeMySQLResource(con, ps, null);
	}

	/**
	 * 
	 * @param ps
	 *            Statement
	 * @param rs
	 *            ResultSet
	 * @return
	 */
	public boolean closeMySQLResource(Statement ps, ResultSet rs) {
		return closeMySQLResource(null, ps, rs);
	}

	/**
	 * 
	 * @param con
	 *            Connection
	 * @param rs
	 *            ResultSet
	 * @return
	 */
	public boolean closeMySQLResource(Connection con, ResultSet rs) {
		return closeMySQLResource(con, null, rs);
	}

	/**
	 * 
	 * @param con
	 *            Connection
	 * @param ps
	 *            Statement
	 * @param rs
	 *            ResultSet
	 * @return
	 */
	public boolean closeMySQLResource(Connection con, Statement ps, ResultSet rs) {
		try {
			if (con != null)
				con.close();
			if (ps != null)
				ps.close();
			if (rs != null)
				rs.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}