1. 程式人生 > >JDBC連線資料庫工具類以及測試

JDBC連線資料庫工具類以及測試

1. 資料庫連線工具程式碼

package com.zzm.db;

import java.sql.*;

/**
 * Created by ming on 2017/6/13.
 */
public class DBUtil {
    //載入驅動
    private final static String DRIVER_CLASS = "com.mysql.jdbc.Driver";

    private  final static String CONN_STR = "jdbc:mysql://localhost:3306/shiro";

    private final static
String USER = "root"; private final static String PWD = "123456"; static { try { Class.forName(DRIVER_CLASS); } catch (ClassNotFoundException e) { //e.printStackTrace(); } } //獲取資料庫連線 public static Connection getConn(){ try
{ return DriverManager.getConnection(CONN_STR); } catch (SQLException e) { e.printStackTrace(); } //System.out.println("執行Connection"); return null; } public static void closeConn(ResultSet rs, PreparedStatement ps,Connection ct){ try
{ if(rs!=null){ rs.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if(ps!=null){ ps.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if(ct!=null){ ct.close(); } } catch (SQLException e) { e.printStackTrace(); } } }

2.測試

package example;
import com.zzm.db.DBUtil;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
import java.sql.*;

/**
 * Created by ming on 2017/6/13.
 */
@WebService()
public class HelloWorld {
  @WebMethod
  public String sayHelloWorldFrom(String from) {
    String result = "Hello, world, from " + from;
    System.out.println(result);
    return result;
  }
  public static void main(String[] argv) {
    /*Object implementor = new HelloWorld ();
    String address = "http://localhost:9000/HelloWorld";
    Endpoint.publish(address, implementor);*/

    HelloWorld hw = new HelloWorld();
    hw.findUserById();
  }

  public String findUserById(){
    try {
      Connection ct = DBUtil.getConn();

      String sql = "select * from users";
      PreparedStatement ps = ct.prepareStatement(sql);
      ResultSet rs = ps.executeQuery();
      System.out.println();
      while (rs.next()){
        int id =  rs.getInt("id");
        String name = rs.getString("userName");
        System.out.println("MYSQL資料庫查出資料->"+id+"->"+name);
      }
      DBUtil.closeConn(rs,ps,ct);
    } catch (SQLException e) {
      e.printStackTrace();
    }
    System.out.println("【執行】");
    return  null;
  }
}