JDBC插入数据使用索引与否的差别

本文展示了一个使用Java进行MySQL数据库批量插入操作的性能测试案例。通过读取文本文件的内容并将其插入到两个不同的测试表中(其中一个使用索引,另一个不使用),对比了两种情况下的执行效率。结果显示,在本次测试中,未使用索引的表在批量插入大量数据时表现出了轻微的优势。

代码:

import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
public class Compare {

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e){
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws FileNotFoundException, IOException, SQLException {
		try (BufferedReader fis = new BufferedReader(new FileReader("D:\\冰与火之歌.txt"))){
			char[] buffer = new char[5];
			int len,count=0;
			String str=null;
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
			Statement stmt = conn.createStatement();
			long begintime = System.currentTimeMillis();
			while((len=fis.read(buffer))!=-1){
				str = String.valueOf(buffer);
				stmt.executeUpdate("insert into test_2 values("+count+",'"+str+"')"); //test_1使用索引, test_2反之
				count++;
				if (count==100000) break;
			}
			long endtime = System.currentTimeMillis();
			System.out.println("耗时:"+(endtime-begintime)+"毫秒");
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

test_1耗时:6980毫秒

test_2耗时:6703毫秒

不知道口乍回事,明天改

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值