格式化

廣告

廣告2

2014年3月17日 星期一

[JAVA教學範例] JAVA JDBC連接MySQL範例類別


這篇是針對MySQL所使用,所以先上網站下載MySQL Connector/J

安裝完會自動在你原本安裝MySQL的路徑下多一個MySQL Connector J資料夾
而裡面有一個mysql-connector-java-5.x.xx-bin.jar檔案便是關鍵
將此.jar檔導入到你的JAVA專案吧


import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

public class MySQL
{
    private java.sql.Connection conDB;
    private java.sql.Statement stat = null;
    private ResultSet rs = null;
    private PreparedStatement pst = null;

    MySQL()
    {
 try
 {
     Class.forName("com.mysql.jdbc.Driver");
     conDB = DriverManager.getConnection("jdbc:mysql://localhost/news?useUnicode=true&characterEncoding=UTF8", "root", "/--z3619861A");
 }
 catch (ClassNotFoundException e)
 {
     System.out.println("DriverClassNotFound :" + e.toString());
 }
 catch (SQLException x)
 {
     System.out.println("Exception :" + x.toString());
 }

    }

    public ResultSet query(String selectSQL)
    {
 try
 {
     stat = conDB.createStatement();
     rs = stat.executeQuery(selectSQL);
     return rs;
 }
 catch (SQLException e)
 {
     System.out.println("queryDB Exception :" + e.toString());
 }
 return null;
    }

    public void insert(String sql)
    {
 try
 {
     pst = conDB.prepareStatement(sql);
     pst.executeUpdate();
 }
 catch(MySQLIntegrityConstraintViolationException e)
 {
     System.out.println("InsertDB Exception :" + e.toString());
     e.printStackTrace();
 }
 catch (SQLException e)
 {
     System.out.println("InsertDB Exception :" + e.toString());
     e.printStackTrace();
 }

 finally
 {
     Close();
 }
    }

    private void Close()
    {
 try
 {
     if (rs != null)
     {
  rs.close();
  rs = null;
     }
     if (stat != null)
     {
  stat.close();
  stat = null;
     }
     if (pst != null)
     {
  pst.close();
  pst = null;
     }
 }
 catch (SQLException e)
 {
     System.out.println("Close Exception :" + e.toString());
 }
    }
}

沒有留言 :