我正在创建一个程序,我将从文本文件中读取数据并将表存储在mysql中。在我的文件中,数据如图所示:
程序要做的是,首先用户给出目录,程序在其中搜索文本文件,然后创建一个包含两个字段(ID,NAME)的表,然后在其中插入值。所有文件都具有相同的结构。 ID位于第三行,名称位于第五行。
有人可以帮我解决在表格中插入这些值的问题吗?我的代码中的“错误”在哪里? 我的程序代码如下:
public static void main(String args[]) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3808/mydb", "root", "root");
String dirpath = "";
Scanner scanner1 = new Scanner(System.in);
while (true) {
System.out.println("Please give the directory:");
dirpath = scanner1.nextLine();
File fl = new File(dirpath);
if (fl.canRead())
break;
System.out.println("Error:Directory does not exists");
}
try {
String files;
File folder = new File(dirpath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
List<File> txtFiles = new ArrayList<File>();
txtFiles.add(listOfFiles[i]);
String[] parts = files.split("\\.");
String tablename = parts[0];
DatabaseMetaData dm = (DatabaseMetaData) con
.getMetaData();
ResultSet rs = dm
.getTables(null, null, tablename, null);
if (!rs.next()) {
System.out.println("The table '" + tablename
+ "' just created. The data are:");
} else {
System.out.println("The table '" + tablename
+ "' already exists.");
continue;
}
for (File txtFile : txtFiles) {
List sheetData = new ArrayList();
try {
FileReader in = new FileReader(txtFile);
BufferedReader br = new BufferedReader(in);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
getCreateTable1(con, tablename);
{
BufferedReader br = new BufferedReader(
new FileReader((txtFile)));
String currentLine = br.readLine();
Map<Integer, String> Fields = new HashMap<Integer, String>();
while (currentLine != null) {
String[] tokens = currentLine.split("\t");
int id = Integer.parseInt(tokens[2]);
String name = tokens[4];
Fields.put(id, name);
currentLine = br.readLine();
}
}
importData(con, txtFile, tablename);
}
}
}
}
} catch (Exception e) {
System.out.println();
}
}
和导入功能的代码是:
private static String importData(Connection con, File txtFile,
String tablename) {
Map<Integer, String> Fields = new HashMap<Integer, String>();
try {
Statement stmt = con.createStatement();
String all = org.apache.commons.lang3.StringUtils.join(Fields, ",");
String sql = "INSERT INTO " + tablename + " VALUES (" + all + ")";
stmt.executeUpdate(sql);
System.out.println("Fill table...");
} catch (Exception e) {
System.out.println(((SQLException) e).getSQLState());
System.out.println(e.getMessage());
e.printStackTrace();
}
return null;
}
}
答案 0 :(得分:1)
我相信您正在创建的查询字符串出现问题。值是整数和字符串,因此请确保您的字符串值包装在单引号中。尝试调试代码或打印&#39; sql&#39;变量。更好的方法是使用PreparedStatement,它可以消除很少的问题。
答案 1 :(得分:0)
您正在使用在运行时不接受输入参数的Statement而是使用Prepared Statement