我正在尝试使用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();
}
}
答案 0 :(得分:0)
使用int affectedRows = stmt.executeUpdate();