springboot使用jdbc连接mysql(不用配置文件)

 

1、连接mysql的工具类:

package com.jzproject.common.mysql;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JDBCconnet {

    private static String driver = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/test?userSSL=false&serverTimezone=UTC";
    private static String user = "root";
    private static String pass = "123456";

    public static List<Map<String, Object>> selectList(){
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url ,user, pass);

            String sql = " SELECT * FROM pmw_infolist\n" +
                    "WHERE classid = '17' ";


            Statement statement = conn.createStatement();

            ResultSet r = statement.executeQuery(sql);
            ResultSetMetaData md = r.getMetaData(); //获取结果集
            int columnCount = md.getColumnCount(); //总列数
            while(r.next()){
                Map rowData = new HashMap();

                for (int i = 1; i <= columnCount; i++) {

                    rowData.put(md.getColumnName(i), r.getObject(i));

                }

                list.add(rowData);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        return list;
    }


    public static void main(String[] args){

        List<Map<String, Object>> list = selectList();
        System.out.println(JSONArray.toJSONString(list));
    }
}

 

如果运行报错:java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver

解决办法:配置idea导入连接mysql的jar包

 

 

找到本地maven仓库里的jar包,直接加进来就ok了

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2023-05-30 14:04  下课后我要去放牛  阅读(413)  评论(0编辑  收藏  举报