gpt4 book ai didi

java - 将txt文件写入mySQL数据库

转载 作者:行者123 更新时间:2023-12-02 12:00:42 24 4
gpt4 key购买 nike

我目前正在尝试通过Java程序将txt文件写入mySQL数据库。我的数据库通过 JDBC 驱动程序正确连接,我可以通过该程序创建表等。但是,当我尝试读取文本文件时,我收到此错误消息

java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''FName' , 'SName' , 'DOB') VALUES ('John' , 'McCullough' , '270696')' at line 1

我在 SQL 代码中找不到错误。这是该类的其余代码。任何帮助将不胜感激。

                try (Connection con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword)) {
FileReader file1 = new FileReader("resources/Test.txt");
BufferedReader buffer1 = new BufferedReader(file1);
String read;
while ((read = buffer1.readLine()) != null) {
String[] row = read.split(",");
String fName = row[0];
String sName = row[1];
String DOB = row[2];
String insert = "INSERT INTO chessleague.table1 ('FName' , 'SName' , 'DOB') VALUES ('" + fName + "' , '" + sName + "' , '" + DOB + "')";

ps = con.prepareStatement(insert);

ps.executeUpdate();
ps.close();
}
} catch (Exception ex) {
System.out.println(ex);
}

最佳答案

正如评论中提到的,不要引用列名称。

该代码严重滥用准备好的语句来执行简单的 SQL。 Connection 类有一个 createStatement() 方法,用于创建一个用于文本形式 SQL 命令的简单语句。

Statement stmt = con.createStatement();
stmt.execute("SELECT * from test.t1");

准备好的语句需要一个用于创建 SQL 语句的模板。下面是如何使用准备好的语句命令完成插入的示例。

try (PreparedStatement ps = con.prepareStatement("INSERT INTO chessleague.table1 (FName , SName , DOB) VALUES (?, ?, ?)")) {
ps.setString(0, fName);
ps.setString(1, sName);
ps.setString(2, DOB);
ps.execute();
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
}

关于java - 将txt文件写入mySQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47273872/

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