中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

將CSV文件導進MySQL表格的Java示例

2018-07-20    來源:open-open

容器云強勢上線!快速搭建集群,上萬Linux鏡像隨意使用
將CSV文件中的數(shù)據(jù)導進MySQL表格的Java示例
ImportCsv.java:
package com.examples;

import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

import com.opencsv.CSVReader;

public class ImportCsv
{
	public static void main(String[] args)
	{
			readCsv();
			readCsvUsingLoad();
	}

	private static void readCsv()
	{

		try (CSVReader reader = new CSVReader(new FileReader("upload.csv"), ','); 
                     Connection connection = DBConnection.getConnection();)
		{
				String insertQuery = "Insert into txn_tbl (txn_id,txn_amount, card_number, terminal_id) values (null,?,?,?)";
				PreparedStatement pstmt = connection.prepareStatement(insertQuery);
				String[] rowData = null;
				int i = 0;
				while((rowData = reader.readNext()) != null)
				{
					for (String data : rowData)
					{
							pstmt.setString((i % 3) + 1, data);

							if (++i % 3 == 0)
									pstmt.addBatch();// add batch

							if (i % 30 == 0)// insert when the batch size is 10
									pstmt.executeBatch();
					}
				}
				System.out.println("Data Successfully Uploaded");
		}
		catch (Exception e)
		{
				e.printStackTrace();
		}

	}

	private static void readCsvUsingLoad()
	{
		try (Connection connection = DBConnection.getConnection())
		{

				String loadQuery = "LOAD DATA LOCAL INFILE '" + "C:\\upload.csv" + "' INTO TABLE txn_tbl FIELDS TERMINATED BY ','" + " LINES TERMINATED BY '\n' (txn_amount, card_number, terminal_id) ";
				System.out.println(loadQuery);
				Statement stmt = connection.createStatement();
				stmt.execute(loadQuery);
		}
		catch (Exception e)
		{
				e.printStackTrace();
		}
	}

}


Sample CSV File:
254.23,123456789,12345
2854.00,987654321,87924
8724.03,598767812,56568

Create txn_tbl SQL :

CREATE TABLE `txn_tbl` (
`txn_id`  int(11) NOT NULL AUTO_INCREMENT ,
`txn_amount`  double NOT NULL ,
`card_number`  bigint(20) NOT NULL ,
`terminal_id`  bigint(20) NULL DEFAULT NULL ,
PRIMARY KEY (`txn_id`)
)

標簽: Mysql

版權申明:本站文章部分自網(wǎng)絡,如有侵權,請聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點!
本站所提供的圖片等素材,版權歸原作者所有,如需使用,請與原作者聯(lián)系。

上一篇:javascript 下雪效果 特效

下一篇:dom4j解析xml文件示例