javaweb 測試數據庫連接是否正常


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

public class ConnectionTest {

    public static Connection getConnection() {
        // 定義連接
        Connection connection = null;

        try {
            // 加載驅動
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/數據庫名稱", "用戶名", "密碼");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static List<HashMap<String, Object>> getMysqlData() {
        Connection connection = null;
        // 預執行加載
        PreparedStatement preparedStatement = null;
        // 結果集
        ResultSet resultSet = null;
        //獲取鏈接
        connection = getConnection();

        //准備的sql
        String sqlString = "select * from user";

        List<HashMap<String, Object>> list = new ArrayList<HashMap<String,Object>>();

        try {
            //預編譯
            preparedStatement = connection.prepareStatement(sqlString);
            resultSet = preparedStatement.executeQuery();  //查詢
            HashMap<String, Object> map = null;
            while (resultSet.next()) {    //遍歷結果集
                map = new HashMap<String, Object>();
                map.put("name", resultSet.getString("nickName"));   //獲取字段名稱nickName的值,
                list.add(map);//將nickName的值添加到map中
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    public static void main(String[] args) {
        List<HashMap<String, Object>> mysqlData = getMysqlData();
        for(HashMap<String, Object> map : mysqlData) {
            System.out.println(map.get("name"));  //通過key獲取Value
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM