package org.algorithm.util;

import java.sql.*;
import java.util.List;

/**
 * mysql链接类
 * @Author: bijl
 * @Date: 2018年7月12日-上午10:02:55
 * @Description:
 */
public class MysqlConnector {
    private Connection conn = null;
    
    /**
     * 创建链接
     * @param url
     */
    public MysqlConnector(String url) {
        if (url.indexOf("utf8") == -1)  // 强制使用utf8编码格式
            url = url.trim()+"&useUnicode=true&characterEncoding=utf8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            this.conn = DriverManager.getConnection(url); 
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("初始化数据库连接错误:");
        }
    }
    
    /**
     * 执行sql语句
     * @param sql
     */
    public void execute(String sql) {
        Statement stmt = null;
        try {
            stmt = this.conn.createStatement();
            stmt.execute(sql); // 执行SQL语句
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("执行错误:"+e.getMessage());
        } 
    }
    
    /**
     * 执行sql语句
     * @param sqls
     */
    public void executeBatch(List<String> sqls) {
        Statement stmt = null;
        try {
            stmt = this.conn.createStatement();
            for (String sql : sqls) {
                stmt.addBatch(sql);
            }
            stmt.executeBatch();
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("执行错误:"+e.getMessage());
        } 
    }
    
    /**
     * 查询
     * @param querySql
     * @return
     */
    public ResultSet query(String querySql) {
        Statement stmt = null;
        ResultSet rs = null; 
        try {
            stmt = this.conn.createStatement();
            rs = stmt.executeQuery(querySql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
       return rs;
    }
    
    /*
     * 关闭连接
     */
    public void close() {
        try {
            this.conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取链接conn
     * @return
     */
    public Connection getConn() {
        return this.conn;
    }

}


