gpt4 book ai didi

java - MySQL "LOAD DATA IN File"使用 JDBC Connector/J

转载 作者:行者123 更新时间:2023-11-29 16:23:23 25 4
gpt4 key购买 nike

我正在尝试使用 JDBC 将 CSV 文件加载到 mysql 5.8 中。我正在使用 JDBC Connector/J API。代码片段如下所示。执行此代码后,我想获取插入/更新的记录数。我怎样才能得到这个计数?我必须获取java程序中的详细信息

import com.mysql.cj.jdbc.*;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PricingSynch {

String host = "localhost";
String port = "3310";
String userid = "pricing";
String password = "pricing";
String uploadDirectory = "C:\\\\ProgramData\\\\MySQL\\\\MySQL Server 5.7\\\\Uploads\\\\";
//String uploadDirectory = null;
String uploadFileExtension = ".csv";

String baseQuery = "LOAD DATA INFILE '"+ uploadDirectory +"{fileName}' REPLACE INTO TABLE prc.{dbTable} FIELDS TERMINATED BY ',' LINES TERMINATED BY \'\\n' IGNORE 1 LINES;" ;

JdbcConnection conn = null;
JdbcStatement stmt = null;
ResultSet rs = null;

public PricingSynch(String host, String port, String userid, String password, String folder) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

this.host = host;
this.port = port;
this.userid = userid;
this.password = password;
this.uploadDirectory = folder;
dbConnection();
runQueries();

}

private void runQueries() throws SQLException {
Utils util = new Utils(uploadDirectory);
String fileNames [] = util.getFiles();
String dbTables [] = util.getTableNames();

for (int i=0;i<fileNames.length;i++) {

String sql = baseQuery.replace("{fileName}", fileNames[i]);
sql = sql.replace("{dbTable}", dbTables[i]);
System.out.println(sql);
stmt.executeUpdate(sql);

/*
while(rs.next()) {

System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
*/
//System.out.println(stmt.getUpdateCount());
//System.out.println(stmt.);
//System.out.println(rs.);
//System.out.println(stmt.);
}
}

public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
// TODO Auto-generated method stub

if (args.length == 0) {

new PricingSynch("localhost", "3310", "root", "pricing", "C:\\ProgramData\\MySQL\\MySQL Server 5.7\\Uploads");
}

if (args.length == 4) {

new PricingSynch(args[0], args[1], args[2], args[3], args[4]);
}
}

private void dbConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
conn =(JdbcConnection) DriverManager.getConnection("jdbc:mysql://"+host+"/world?" +"user="+userid+"&password="+password);
stmt = (JdbcStatement)conn.createStatement();
//stmt.getGeneratedKeys().getMetaData();
}
}

最佳答案

使用intaffectRows = stmt.executeUpdate();

关于java - MySQL "LOAD DATA IN File"使用 JDBC Connector/J,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54407490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com