我在R中有代码,它应该生成并运行INSERT查询到本地MySQL数据库。连接有效,因为我能够运行其他几个查询,因此我知道连接和我的方法应该正常工作。我也打印出我正在尝试的查询,然后我粘贴到我的MySQL连接并且它可以工作,所以我不知道为什么R会抛出错误。我该怎么做才能解决这个问题?
查询:
INSERT INTO Strike SET effect = '' , feet_above_ground = '0' ; SET @Strike_id = LAST_INSERT_ID(); Insert INTO Flight SET date = '1/1/00 0:00' , aircraft_type = 'Airplane' , record_id = '200508' , strike_id = @Strike_id , airport_id = (SELECT id FROM Airport WHERE name = 'NEWARK LIBERTY INTL ARPT' ), airline_id = (SELECT id FROM Airline WHERE name = 'CONTINENTAL AIRLINES' ); UPDATE Strike SET flight_id = LAST_INSERT_ID() WHERE id = @Strike_id;
代码:
padValue <- function(value) {
return(paste('"',value,'"', sep=""))
}
insertFlightAndStrike <- function(data, connection=con) {
for(i in 1:nrow(data)) {
row <- data[i,]
effect = padValue(row$Effect..Impact.to.flight)
feet_above_ground = padValue(row$Feet.above.ground)
flight_date = padValue(row$FlightDate)
aircraft_type = padValue(row$Aircraft..Type)
record_id = padValue(row$Record.ID)
airport_name = padValue(row$Airport..Name)
airline_name = padValue(row$Aircraft..Airline.Operator)
query <- paste("INSERT INTO Strike SET effect = ",effect,
", feet_above_ground = ",feet_above_ground,
"; SET @Strike_id = LAST_INSERT_ID(); INSERT INTO Flight SET date = ", flight_date,
", aircraft_type = ", aircraft_type,
", record_id = ", record_id,
", strike_id = @Strike_id",
", airport_id = (SELECT id FROM Airport WHERE name = ", airport_name,
"), airline_id = (SELECT id FROM Airline WHERE name = ", airline_name,");",
"UPDATE Strike SET flight_id = LAST_INSERT_ID() WHERE id = @Strike_id;")
print(gsub("\"","'",query))
dbGetQuery(connection, gsub("\"","'",query))
}
}
错误:
.local(conn,statement,...)出错:无法运行语句:SQL语法中有错误;检查与您的MySQL服务器版本相对应的手册,以便在&#39; SET @Strike_id = LAST_INSERT_ID()附近使用正确的语法;插入INTO航班SET日期=&#39; 1/1/00 0:00&#39; &#39;在第1行
编辑:
尝试在MySQL中使用查询时:
mysql> INSERT INTO Strike SET effect = '' , feet_above_ground = '0' ; SET @Strike_id = LAST_INSERT_ID(); INSERT INTO Flight SET date = '1/1/00 0:00' , aircraft_type = 'Airplane' , record_id = '200508' , strike_id = @Strike_id , airport_id = (SELECT id FROM Airport WHERE name = 'NEWARK LIBERTY INTL ARPT' ), airline_id = (SELECT id FROM Airline WHERE name = 'CONTINENTAL AIRLINES' ); UPDATE Strike SET flight_id = LAST_INSERT_ID() WHERE id = @Strike_id;
Query OK, 1 row affected (0.01 sec)
Query OK, 0 rows affected (0.00 sec)
Query OK, 1 row affected (0.00 sec)
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
答案 0 :(得分:-1)
mysql> SET @Strike_id = LAST_INSERT_ID();
Query OK, 0 rows affected (0.02 sec)
适合我。