DBHelper连接数据库

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DBHelper连接数据库相关的知识,希望对你有一定的参考价值。

  DBHelper连接数据库代码如下

package tools;

import java.io.Console;
import java.sql.*;
import java.util.Enumeration;
//import java.util.logging.*;
//import javax.swing.table.*;

/**
 *  SQL 鍩烘湰鎿嶄綔
 * 閫氳繃瀹?鍙互寰堣交鏉剧殑浣跨敤 JDBC 鏉ユ搷绾垫暟鎹簱
 * @author Null
 */
public class DBHelper
{

 /**
     * 椹卞姩
     */
    //public static String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
    public static String driver = "com.mysql.jdbc.Driver";
    /**
     * 杩炴帴瀛楃涓?
     */
    //public static String url = "jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=st";
    public static String url = "jdbc:mysql://localhost:3306/test";
    /**
     * 鐢ㄦ埛鍚?
     */
    public static String user = "root";
    /**
     * 瀵嗙爜
     */
    public static String password = "root";

    /**
     * 涓嶅厑璁稿疄渚嬪寲璇ョ被
     */
    private DBHelper()
    {
    }

    /**
     * 鑾峰彇涓?釜鏁版嵁搴撹繛鎺?
     * 閫氳繃璁剧疆绫荤殑  driver / url / user / password 杩欏洓涓潤鎬佸彉閲忔潵 璁剧疆鏁版嵁搴撹繛鎺ュ睘鎬?
     * @return 鏁版嵁搴撹繛鎺?
     */
    public static Connection getConnection()
    {
        try
        {
         //鑾峰彇椹卞姩
            Class.forName(driver);
        } catch (ClassNotFoundException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
        }

        try
        {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
            return null;
        }
    }

    /**
     * 鑾峰彇涓?釜 Statement
     * 璇?Statement 宸茬粡璁剧疆鏁版嵁闆?鍙互婊氬姩,鍙互鏇存柊
     * @return 濡傛灉鑾峰彇澶辫触灏嗚繑鍥?null,璋冪敤鏃惰寰楁鏌ヨ繑鍥炲?
     */
    public static Statement getStatement()
    {
        Connection conn = getConnection();
        if (conn == null)
        {
            return null;
        }
        try
        {
            return conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);
        // 閻犱礁澧介悿鍡涘极閻楀牆绁﹂梻鍡楁瑜板弶绂掗妷锔炬硦闁告棑鎷烽柛娆樺灟娴滄帡寮寸?妯荤厐
        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
            close(conn);
        }
        return null;
    }

    /**
     * 鑾峰彇涓?釜 Statement
     * 璇?Statement 宸茬粡璁剧疆鏁版嵁闆?鍙互婊氬姩,鍙互鏇存柊
     * @param conn 鏁版嵁搴撹繛鎺?
     * @return 濡傛灉鑾峰彇澶辫触灏嗚繑鍥?null,璋冪敤鏃惰寰楁鏌ヨ繑鍥炲?
     */
    public static Statement getStatement(Connection conn)
    {
        if (conn == null)
        {
            return null;
        }
        try
        {

            return conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            // 璁剧疆鏁版嵁闆嗗彲浠ユ粴鍔?鍙互鏇存柊
        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
            return null;
        }
    }

    /**
     * 鑾峰彇涓?釜甯﹀弬鏁扮殑 PreparedStatement
     * 璇?PreparedStatement 宸茬粡璁剧疆鏁版嵁闆?鍙互婊氬姩,鍙互鏇存柊
     * @param cmdText 闇? ? 鍙傛暟鐨?SQL 璇彞
     * @param cmdParams SQL 璇彞鐨勫弬鏁拌〃
     * @return 濡傛灉鑾峰彇澶辫触灏嗚繑鍥?null,璋冪敤鏃惰寰楁鏌ヨ繑鍥炲?
     */
    public static PreparedStatement getPreparedStatement(String cmdText, Object[] cmdParams)
    {
        Connection conn = getConnection();
        if (conn == null)
        {
            return null;
        }

        PreparedStatement pstmt = null;
        try
        {
         
            pstmt = conn.prepareStatement(cmdText, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            int i = 1;
            for (Object item : cmdParams) //java foreach閬嶅巻闆嗗悎,瑕佹眰闆嗗悎绫诲疄鐜癊numeration鎺ュ彛
            {
                pstmt.setObject(i, item);
                i++;
            }
        } catch (SQLException e)
        {
            e.printStackTrace();
            close(conn);
        }
        return pstmt;
    }

    /**
     *  鑾峰彇涓?釜甯﹀弬鏁扮殑 PreparedStatement
     * 璇?PreparedStatement 宸茬粡璁剧疆鏁版嵁闆?鍙互婊氬姩,鍙互鏇存柊
     * @param conn 鏁版嵁搴撹繛鎺?
     * @param cmdText 闇? ? 鍙傛暟鐨?SQL 璇彞
     * @param cmdParams SQL 璇彞鐨勫弬鏁拌〃
     * @return 濡傛灉鑾峰彇澶辫触灏嗚繑鍥?null,璋冪敤鏃惰寰楁鏌ヨ繑鍥炲?
     */
    public static PreparedStatement getPreparedStatement(Connection conn, String cmdText, Object[] cmdParams)
    {
        if (conn == null)
        {
            return null;
        }

        PreparedStatement pstmt = null;
        try
        {
            pstmt = conn.prepareStatement(cmdText, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
            int i = 1;
            for (Object item : cmdParams)
            {
                pstmt.setObject(i, item);
                i++;
            }
        } catch (SQLException ex)
        {
         System.out.println(ex.getMessage());
            //ex.printStackTrace();
            close(pstmt);
        }
        return pstmt;
    }

    /**
     * 鎵ц SQL 璇彞,杩斿洖缁撴灉涓烘暣鍨?
     * 涓昏鐢ㄤ簬鎵ц闈炴煡璇㈣鍙?
     * @param cmdText SQL 璇彞
     * @return 闈炶礋鏁?姝e父鎵ц; -1:鎵ц閿欒; -2:杩炴帴閿欒
     */
    public static int ExecSql(String cmdText)
    {
        Statement stmt = getStatement();
        if (stmt == null)
        {
            return -2;
        }
        int i;
        try
        {
            i = stmt.executeUpdate(cmdText);
        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null,ex);
         System.out.println(ex.getMessage());
            i = -1;
        }
        closeConnection(stmt);
        return i;
    }

    /**
     * 鎵ц SQL 璇彞,杩斿洖缁撴灉涓烘暣鍨?
     * 涓昏鐢ㄤ簬鎵ц闈炴煡璇㈣鍙?
     * @param cmdText SQL 璇彞
     * @return 闈炶礋鏁?姝e父鎵ц; -1:鎵ц閿欒; -2:杩炴帴閿欒
     */
    public static int ExecSql(Connection conn, String cmdText)
    {
        Statement stmt = getStatement(conn);
        if (stmt == null)
        {
            return -2;
        }
        int i;
        try
        {
            i = stmt.executeUpdate(cmdText);

        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
        
            i = -1;
        }
        close(stmt);
        return i;
    }

    /**
     * 鎵ц SQL 璇彞,杩斿洖缁撴灉涓烘暣鍨?
     * 涓昏鐢ㄤ簬鎵ц闈炴煡璇㈣鍙?
     * @param cmdText 闇? ? 鍙傛暟鐨?SQL 璇彞
     * @param cmdParams SQL 璇彞鐨勫弬鏁拌〃
     * @return 闈炶礋鏁?姝e父鎵ц; -1:鎵ц閿欒; -2:杩炴帴閿欒
     */
    public static int ExecSql(String cmdText, Object[] cmdParams)
    {
        PreparedStatement pstmt = getPreparedStatement(cmdText, cmdParams);
        if (pstmt == null)
        {
            return -2;
        }
        int i;
        try
        {
            i = pstmt.executeUpdate();
        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
           i = -1;
        }
        closeConnection(pstmt);
        return i;
    }

    /**
     * 鎵ц SQL 璇彞,杩斿洖缁撴灉涓烘暣鍨?
     * 涓昏鐢ㄤ簬鎵ц闈炴煡璇㈣鍙?
     * @param conn 鏁版嵁搴撹繛鎺?
     * @param cmdText 闇? ? 鍙傛暟鐨?SQL 璇彞
     * @param cmdParams SQL 璇彞鐨勫弬鏁拌〃
     * @return 闈炶礋鏁?姝e父鎵ц; -1:鎵ц閿欒; -2:杩炴帴閿欒
     */
    public static int ExecSql(Connection conn, String cmdText, Object[] cmdParams)
    {
        PreparedStatement pstmt = getPreparedStatement(conn, cmdText, cmdParams);
        if (pstmt == null)
        {
            return -2;
        }
        int i;
        try
        {
            i = pstmt.executeUpdate();

        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
            i = -1;
        }
        close(pstmt);
        return i;
    }

    /**
     * 杩斿洖缁撴灉闆嗙殑绗竴琛岀殑涓?垪鐨勫?,鍏朵粬蹇界暐
     * @param cmdText SQL 璇彞
     * @return
     */
    public static Object ExecScalar(String cmdText)
    {
        ResultSet rs = getResultSet(cmdText);
        Object obj = getScalar(rs);
        closeConnection(rs);
        return obj;
    }

    /**
     * 杩斿洖缁撴灉闆嗙殑绗竴琛岀殑涓?垪鐨勫?,鍏朵粬蹇界暐
     * @param conn 鏁版嵁搴撹繛鎺?
     * @param cmdText SQL 璇彞
     * @return
     */
    public static Object ExecScalar(Connection conn, String cmdText)
    {
        ResultSet rs = getResultSet(conn, cmdText);
        Object obj = getScalar(rs);
        closeEx(rs);
        return obj;
    }

    /**
     * 杩斿洖缁撴灉闆嗙殑绗竴琛岀殑涓?垪鐨勫?,鍏朵粬蹇界暐
     * @param cmdText 闇? ? 鍙傛暟鐨?SQL 璇彞
     * @param cmdParams SQL 璇彞鐨勫弬鏁拌〃
     * @return
     */
    public static Object ExecScalar(String cmdText, Object[] cmdParams)
    {
        ResultSet rs = getResultSet(cmdText, cmdParams);
        Object obj = getScalar(rs);
        closeConnection(rs);
        return obj;
    }

    /**
     * 杩斿洖缁撴灉闆嗙殑绗竴琛岀殑涓?垪鐨勫?,鍏朵粬蹇界暐
     * @param conn 鏁版嵁搴撹繛鎺?
     * @param cmdText 闇? ? 鍙傛暟鐨?SQL 璇彞
     * @param cmdParams SQL 璇彞鐨勫弬鏁拌〃
     * @return
     */
    public static Object ExecScalar(Connection conn, String cmdText, Object[] cmdParams)
    {
        ResultSet rs = getResultSet(conn, cmdText, cmdParams);
        Object obj = getScalar(rs);
        closeEx(rs);
        return obj;
    }

    /**
     * 杩斿洖涓?釜 ResultSet
     * @param cmdText SQL 璇彞
     * @return
     */
    public static ResultSet getResultSet(String cmdText)
    {
        Statement stmt = getStatement();
        if (stmt == null)
        {
            return null;
        }
        try
        {
            return stmt.executeQuery(cmdText);
        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
           closeConnection(stmt);
        }
        return null;
    }

    /**
     * 杩斿洖涓?釜 ResultSet
     * @param conn
     * @param cmdText SQL 璇彞
     * @return
     */
    public static ResultSet getResultSet(Connection conn, String cmdText)
    {
        Statement stmt = getStatement(conn);
        if (stmt == null)
        {
            return null;
        }
        try
        {
            return stmt.executeQuery(cmdText);
        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
            close(stmt);
        }
        return null;
    }

    /**
     * 杩斿洖涓?釜 ResultSet
     * @param cmdText 闇? ? 鍙傛暟鐨?SQL 璇彞
     * @param cmdParams SQL 璇彞鐨勫弬鏁拌〃
     * @return
     */
    public static ResultSet getResultSet(String cmdText, Object[] cmdParams)
    {
        PreparedStatement pstmt = getPreparedStatement(cmdText, cmdParams);
        if (pstmt == null)
        {
            return null;
        }
        try
        {
            return pstmt.executeQuery();
        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
            closeConnection(pstmt);
        }
        return null;
    }

    /**
     * 杩斿洖涓?釜 ResultSet
     * @param conn 鏁版嵁搴撹繛鎺?
     * @param cmdText 闇? ? 鍙傛暟鐨?SQL 璇彞
     * @param cmdParams SQL 璇彞鐨勫弬鏁拌〃
     * @return
     */
    public static ResultSet getResultSet(Connection conn, String cmdText, Object[] cmdParams)
    {
        PreparedStatement pstmt = getPreparedStatement(conn, cmdText, cmdParams);
        if (pstmt == null)
        {
            return null;
        }
        try
        {
            return pstmt.executeQuery();
        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
            close(pstmt);
        }
        return null;
    }

    public static Object getScalar(ResultSet rs)
    {
        if (rs == null)
        {
            return null;
        }
        Object obj = null;
        try
        {
            if (rs.next())
            {
                obj = rs.getObject(1);
            }
        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
        }
        return obj;
    }
 
    private static void close(Object obj)
    {
        if (obj == null)
        {
            return;
        }
        try
        {
            if (obj instanceof Statement)
            {
                ((Statement) obj).close();
            } else if (obj instanceof PreparedStatement)
            {
                ((PreparedStatement) obj).close();
            } else if (obj instanceof ResultSet)
            {
                ((ResultSet) obj).close();
            } else if (obj instanceof Connection)
            {
                ((Connection) obj).close();
            }
        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
       }
    }

 

 

 

    private static void closeEx(Object obj)
    {
        if (obj == null)
        {
            return;
        }

        try
        {
            if (obj instanceof Statement)
            {
                ((Statement) obj).close();
            } else if (obj instanceof PreparedStatement)
            {
                ((PreparedStatement) obj).close();
            } else if (obj instanceof ResultSet)
            {
                ((ResultSet) obj).getStatement().close();
            } else if (obj instanceof Connection)
            {
                ((Connection) obj).close();
            }
        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
        }

    }

    private static void closeConnection(Object obj)
    {
        if (obj == null)
        {
            return;
        }
        try
        {
            if (obj instanceof Statement)
            {
                ((Statement) obj).getConnection().close();
            } else if (obj instanceof PreparedStatement)
            {
                ((PreparedStatement) obj).getConnection().close();
            } else if (obj instanceof ResultSet)
            {
                ((ResultSet) obj).getStatement().getConnection().close();
            } else if (obj instanceof Connection)
            {
                ((Connection) obj).close();
            }
        } catch (SQLException ex)
        {
            //Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println(ex.getMessage());
       }
    }
}

 实现实体类代码如下

package entity;
public class User{
 private String userID;
 private String userName;
 private String password;

 public void setUserID(String userID){
  this.userID=userID;
 }
 public String getUserID(){
  return userID;
 }

 public void setUserName(String userName){
  this.userName=userName;
 }
 public String getUserName(){
  return userName;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
}

 

写完

private String userID;
 private String userName;
 private String password;

getset即可

以上是关于DBHelper连接数据库的主要内容,如果未能解决你的问题,请参考以下文章

数据库连接通用DBHelper类

3月9日(用 DBHelper 工具连接 mysql 数据库 实现登录验证)

DBHelper.java(数据库连接类)

DBHelper类连接数据库

t4必须DbHelper.ttinclude t4连接数据库获取表必须

EF事务嵌套