极速 csv文件导入Mysql

第一步:创建项目、导入包如图:
commons-lang3-3.8.1.jar
mysql-connector-java-8.0.26.jar
opencsv-5.5.2.jar
在这里插入图片描述

第二步:实现连接Mysql
package com.excel.utils;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBUtils {
/**
* URL."
/
private static String URL = “jdbc:mysql://IP:端口/数据库名?characterEncoding=UTF-8&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai&useSSL=false”;
/
*
* USERNAME.
/
private static String USERNAME = “用户名”;
/
*
* PASSWORD.
*/
private static String PASSWORD = “密码”;

/**
 * conn.
 */
private static Connection conn;
/**
 * DRIVER_CLASS.
 */
private static String DRIVER_CLASS = "com.mysql.cj.jdbc.Driver";

/**
 * 根据配置文件,获取数据库连接
 * 
 * @param configFile
 * @return
 * @throws Exception
 */
public static Connection getConnection(final String configFile) throws Exception {
	if (conn == null) {
		Class.forName(DRIVER_CLASS);
		conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		return conn;
	} else {
		return conn;
	}
}

/**
 * 根据配置文件,获取数据库连接
 * 
 * @param configFile
 * @return
 * @throws Exception
 */
public static Connection getConnection() throws Exception {
	if (conn == null) {
		Class.forName(DRIVER_CLASS);
		conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		return conn;
	} else {
		return conn;
	}
}

}

第三步:实现导入数据库
package com.excel.utils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;

import com.opencsv.CSVReader;

public class ImportDataForMysql {

public static void main(String[] args) {
	String csvFilePath ="";
	String tablename = "";  
	csvFilePath = "2023-09-14.csv";
	tablename = "TaskA1_20230913";
	inputData(csvFilePath,tablename);
}

public static void inputData(String csvFilePath, String tableName) {
   // 替换为你的CSV文件路径
    try (Connection connection = getConn();
         BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {
        // 读取CSV文件第一行作为表头
        String headerLine = br.readLine();
        List<String> headers = Arrays.asList(headerLine.split(","));
        dropTable(connection, headers,tableName);
        // 建立表格并获取动态的列定义
        createTable(connection, headers,tableName);
        // 使用 OpenCSV 读取 CSV 文件数据
        CSVReader csvReader = new CSVReader(br);
        List<String[]> rows = csvReader.readAll();
        // 将STS数据插入到表中
        insertDataIntoTable(connection, headers, rows,tableName);

        System.out.println("数据导入完成!");

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

public static Connection getConn() throws Exception {
	Connection conn= DBUtils.getConnection();
	return conn;
}


private static void dropTable(Connection connection, List<String> headers,String table) throws SQLException {
	try {
		StringBuilder sb = new StringBuilder();
        sb.append("Drop TABLE "+table+";"); 
        try (Statement statement = connection.createStatement()) {
            statement.executeUpdate(sb.toString());
        }
	} catch (Exception e) {
		e.printStackTrace();
	}
    
}


public static String maxlenStr = "";
public static String findLongestString(String oldstring, String newString) {
	String longestString = "";
	int maxLength = oldstring.length();
	if (newString.length() > maxLength) {
		maxLength = newString.length();
		longestString = newString;
	}
	maxlenStr = longestString;
	return longestString;
}

private static void createTable(Connection connection, List<String> headers,String table) throws SQLException {
    StringBuilder sb = new StringBuilder();
    sb.append("CREATE TABLE "+table+ " (");
    for (String header : headers) {
        sb.append("`"+header+"`").append(" varchar(200),");
    }
    sb.deleteCharAt(sb.length() - 1);
    sb.append(")");
    System.out.println(sb.toString());

    try (Statement statement = connection.createStatement()) {
        statement.executeUpdate(sb.toString());
    }
}

private static void insertDataIntoTable(Connection connection, List<String> headers, List<String[]> data,String tableName) throws SQLException {
    StringBuilder sb = new StringBuilder();
    sb.append("INSERT INTO "+tableName+" (");
    for (String header : headers) {
        sb.append("`"+header+"`").append(",");
    }
    sb.deleteCharAt(sb.length() - 1);
    sb.append(") VALUES (");
    
    for (String header : headers) {
        sb.append("?").append(",");
    }
    sb.deleteCharAt(sb.length() - 1);

    String sql = sb.toString();
    sql += ")";
    System.out.println(sql);
    try (PreparedStatement statement = connection.prepareStatement(sql)) {
        for (String[] row : data) {
            for (int i = 0; i < row.length; i++) {
            	String col = row[i];
            	findLongestString(maxlenStr, col);
                statement.setString(i + 1, row[i]);
            }
            statement.executeUpdate();
        }
    }
    System.out.println(maxlenStr);
}

}

第四步:效果图
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值