Java jdbc连接数据库

发布时间:2020-03-28 09:11:14 作者:Mos 阅读量:1022

连接工具:

package db;

import java.sql.*;

public class MovieDb {
    private static final String URL = "jdbc:mysql://xxxx:3306/xxx?autoReconnect=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false";
    private static final String UNAME = "xxx";
    private static final String PWD = "xx";

    private static Connection conn = null;

    static {
        try {
            // 1.加载驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.获得数据库的连接
            conn = DriverManager.getConnection(URL, UNAME, PWD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        return conn;
    }

    public static void closeConnection(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
} 

使用方法:

package deal;

import db.MovieDb;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MovieDeal {
    public static List<Map> getToday() {
        List<Map> movies = new ArrayList<Map>();
        Connection movieConn = null;
        PreparedStatement moviePs = null;
        ResultSet movieRs = null;
        try {
            movieConn = MovieDb.getConnection();
            moviePs = movieConn.prepareStatement("sql");
            movieRs = moviePs.executeQuery();
            while (movieRs.next()) {
                Map<String,String> map = new HashMap<String, String>();
                map.put("type_name",movieRs.getString("type_name")); movies.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MovieDb.closeConnection(movieConn, moviePs, movieRs);
        }
        return movies;
    }
}



支付宝打赏 微信打赏
©2021 i847.cn
部分内容转自网络,如有损害您的权益,致邮联系:jiang2008wen#126.com,一经证实,立即删除!     我要留言
备案号:蜀ICP备18020563号-1