目前我正在尝试通过 Apache Derby 将新数据传递到 SQL 表。我将从具有给定文本的文件中读取,并将读取的每个标记添加到其各自的列中。但是,在尝试执行此操作时,我收到许多错误,表明令牌不是列……但这不是我想要做的。carmpg.txt 内容:Toyota Prius 52 23475Kia Optima 31 22600Hyundai Sonata 31 22050Nissan Altima 31 23260Chevrolet Malibu 30 21680Honda Accord 30 23570Mazda 6 29 21945Subaru Legacy 29 22195Toyota Camry 27 23495Chrysler 200 27 22115Ford Fusion 27 22120Volkswagen Passat 27 22995Volkswagen CC 25 34475Chevrolet Impala 25 27895Buick LaCrosse 25 29565Nissan Maxima 25 33270Buick Regal 24 27065Lincoln MKZ 26 3560所以,Toyota应该进入Manufacturer专栏,Prius应该进入Model专栏,等等。这是代码: try(Connection conn = SimpleDataSource.getConnection();Statement stat = conn.createStatement()) { try { stat.execute("DROP TABLE Car"); } catch(SQLException e) { // get exception if table doesn't exist yet } stat.execute("CREATE TABLE Car (Manufacturer VARCHAR(20)," + "Model VARCHAR(20), " + "Efficiency DECIMAL(6,2), " + "Price DECIMAL(8,2)) "); String inputFileName = "carmpg.txt"; File inputFile = new File(inputFileName); Scanner in = new Scanner(inputFile); // COMPLETE THIS WHILE LOOP to insert all cars from the input text file while (in.hasNextLine()){ stat.execute("INSERT INTO Car VALUES " + in.next()); } ResultSet rs = stat.executeQuery("SELECT * FROM Car"); rs.next(); System.out.println(rs.getString("Model"));
1 回答
摇曳的蔷薇
TA贡献1793条经验 获得超6个赞
INSERT INTO
语句的语法是:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
另外你的错误是你试图从文本文件中插入整行而不将它分成代表 4 个不同列的 4 个部分。
由于您尝试执行此无效语句,因此触发了您收到的错误:
INSERT INTO Car VALUES Toyota Prius 52 23475
它应该是
INSERT INTO Car (Manufacturer, Model, Efficiency, Price) VALUES ('Toyota', 'Prius', 52, 23475)
添加回答
举报
0/150
提交
取消