jdbc批量导入数据

java链接mysql批量导入数据

package MysqlDemo;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;

public class mysqlTest {
	static Connection conn;
	static Statement stat;

	public static void main(String[] args) throws Exception {
		String filePath = "d:\\sc.txt";
		jdbcLink();// 数据库链接
		readFileContent(filePath);
	}

	private static void readFileContent(String filePath) throws Exception {
		// 读取文件,转为缓冲流
		BufferedReader br = new BufferedReader(new FileReader(filePath));
		// 1.将读取到的信息存入到集合
		ArrayList<String> list1 = new ArrayList<String>();
		String result;
		while ((result = br.readLine()) != null) {
			list1.add(result);
		}
		br.close();
		// 2.处理读到语句为标准sql语句
		ArrayList<String> list2 = new ArrayList<String>();
		for (int i = 0; i < list1.size(); i++) {
			String res = list1.get(i);
			String[] split = res.split(",");
			// 改装为sql
			String sql = getSql(split);
			stat.executeUpdate(sql);
		}

	}

	private static String getSql(String[] split) {
		// 改装为sql
		String sql = "insert sc values(" + split[0] + "," + split[1] + "," + split[2] + ")";
		return sql;
	}

	private static void jdbcLink() throws Exception {
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/STUDENT";
		String username = "hyt";
		String password = "123456";
		// 注册
		Class.forName(driver); // classLoader,加载对应驱动
		// 获取mysql连接点
		conn = DriverManager.getConnection(url, username, password);
		// 创建与mysql交互对象
		stat = conn.createStatement();
	}
}

测试数据:sc.txt//可保存为txt文本
95007,3,68
95007,4,91
95007,5,94
95007,6,78
95008,1,98
95008,3,89
95008,6,91
95009,2,81
95009,4,89
95009,6,100
95010,2,98
95010,5,90
95010,6,80
95011,1,81
95011,2,91
95011,3,81
95011,4,86
95012,1,81
95012,3,78
95012,4,85
95012,6,98
95013,1,98
95013,2,58
95013,4,88
95013,5,93
95014,1,91
95014,2,100
95014,4,98
95015,1,91
95015,3,59
95015,4,100
95015,6,95
95016,1,92
95016,2,99
95016,4,82
95017,4,82
95017,5,100
95017,6,58
95018,1,95
95018,2,100
95018,3,67
95018,4,78
95019,1,77
95019,2,90
95019,3,91
95019,4,67
95019,5,87
95020,1,66
95020,2,99
95020,5,93
95021,2,93
95021,5,91
95021,6,99
95022,3,69
95022,4,93
95022,5,82
95022,6,100
全部评论
请问可以请教一下导入导出数据的问题嘛?
点赞 回复 分享
发布于 2020-04-14 00:13

相关推荐

06-25 16:00
武汉大学 Java
工科研究生底薪工资就开3k啊??
机械打工仔:写文章提成的岗位工资低,你怪工科?
点赞 评论 收藏
分享
在开会的单身狗很有一套:学院本被想着这么快有面试,而且简历废话太多了 那些在校经历什么荣誉什么的企业不关心
点赞 评论 收藏
分享
06-20 17:42
东华大学 Java
凉风落木楚山秋:要是在2015,你这简历还可以月入十万,可惜现在是2025,已经跟不上版本了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务