2013年7月16日 星期二

java jdbc mysql

import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class jdbcmysql {
  private Connection con = null; //Database objects
  private Statement stat = null;
  private ResultSet rs = null;
  private PreparedStatement pst = null;
  private String dropdbSQL = "";
  static String createdbSQL = "";
  static String insertdbSQL = "";
   private String selectSQL = "";

  public jdbcmysql()
  {
    try {
      Class.forName("com.mysql.jdbc.Driver");
      con = DriverManager.getConnection("jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=UTF8","root","root");
    }
    catch(ClassNotFoundException e)
    {
      System.out.println("DriverClassNotFound :"+e.toString());
    }
    catch(SQLException x) {
      System.out.println("Exception :"+x.toString());
    }
  
  }
  public void RunMySql()  throws SQLException
  {
    try
    {
      stat = con.createStatement();
      stat.executeUpdate(createdbSQL);
    }
    //catch(SQLException e){System.out.println (createdbSQL); System.out.println("CreateDB Exception :" + e.toString());}
    finally
    {
      Close();
    }
  }

  public void dropTable()
  {
    try
    {
      stat = con.createStatement();
      stat.executeUpdate(dropdbSQL);
    }
    catch(SQLException e)
    {
      System.out.println("DropDB Exception :" + e.toString());
    }
    finally
    {
      Close();
    }
  }
  public void SelectTable()
  {
    try
    {
      stat = con.createStatement();
      rs = stat.executeQuery(selectSQL);
      System.out.println("ID\t\tName\t\tPASSWORD");
      while(rs.next())
      {
        System.out.println(rs.getInt("id")+"\t\t"+
            rs.getString("name")+"\t\t"+rs.getString("passwd"));
      }
    }
    catch(SQLException e) {System.out.println("DropDB Exception :" + e.toString());}
    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());
    }
  }
}

沒有留言:

張貼留言