JDBC连接数据库工具类以及测试

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/windzzm/article/details/73176606

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;
  }
}

猜你喜欢

转载自blog.csdn.net/windzzm/article/details/73176606