1. 程式人生 > >MySQL資料連線,關閉,還有設定資料庫的編碼方式

MySQL資料連線,關閉,還有設定資料庫的編碼方式

package UserManager; /**
 * Created by mff on 2017/5/15.
 */
import java.sql.*;
public class MysqlConnect {
    public static Connection connectMysql() {
        // 驅動程式名
       // String driver = "com.mysql.jdbc.Driver";
String driver = "com.mysql.cj.jdbc.Driver";
// URL指向要訪問的資料庫,並設定編碼方式為UTF-8
String url = "jdbc:mysql://localhost/myDataBase?useUnicode=true&characterEncoding=UTF-8"
; // MySQL配置時的使用者名稱 String user = "root"; // MySQL配置時的密碼 String password = "1234"; Connection conn = null; try { // 載入驅動程式 Class.forName(driver); // 連線資料庫 conn = DriverManager.getConnection(url, user, password); if (!conn.isClosed()) System.out.println("Succeeded connecting to the Database!"
); } catch (ClassNotFoundException e) { System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return conn; } /** * 關閉conn * *
@param conn */ public static void close(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 關閉PreparedStatement * * @param pstmt */ public static void close(PreparedStatement pstmt) { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 關閉ResultSet * @param rs */ public static void close(ResultSet rs ) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void main(String[] args) { //測試資料庫連線 Connection connection=connectMysql(); } }