我目前得到以下查询,我想用它来插入两个字符串和一个外键。但是,当我传递外键的字符串时,我想在插入时获取密钥,因此记录实际上将显示为:
“All Asia Asset Cp”,“AAA”,1
以下是我使用的字符串:
String sql = "INSERT into constituent " +
"(constituent_name, constituent_ticker, sector_id) values (\""+
constituent.getConstituentName() + "\",\"" +
constituent.getConstituentTicker() + "\"," +
"(select id from sector where sector_name = \"" + constituent.getConstituentSector() + "\"))";
以下是查询。
INSERT into constituent (constituent_name, constituent_ticker, sector_id)
values ("All Asia Asset Cp","AAA",
(select sector.id from sector where sector_name = "General Financial Sector"))
然而,我得到以下错误,我很难过。有什么想法吗?
Unknown column 'sector.id' in 'field list'
在phpMyAdmin中按原样运行查询。
使用以下命令从java运行它会引发错误:
//Initialize insertValues
insertValues = connect.prepareStatement(sql);
//Attempt to add the values into the database
try {
insertValues.execute();
} catch (Exception e) {
Log.e(CLASS_NAME, "createConstituent ", e);
}
DDL对于扇区表:
CREATE TABLE `sector` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`sector_name` varchar(100) DEFAULT NULL,
`sector_url` varchar(500) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=latin1;
DDL对于组成表:
CREATE TABLE `constituent` (
`constituent_id` int(11) NOT NULL AUTO_INCREMENT,
`constituent_name` varchar(100) DEFAULT '',
`constituent_ticker` varchar(10) NOT NULL,
`constituent_isin_number` varchar(50) DEFAULT '',
`constituent_currency` varchar(10) DEFAULT '',
`sector_id` int(11) NOT NULL,
PRIMARY KEY (`constituent_id`),
KEY `sector_id` (`sector_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
答案 0 :(得分:0)
而不是sector.id,你可以尝试只使用id。可能是吗?
INSERT into constituent (constituent_name, constituent_ticker, sector_id) values ("All Asia Asset Cp","AAA",(select id from sector where sector_name = "General Financial Sector"))
答案 1 :(得分:0)
试试这个查询..
INSERT into constituent (constituent_name, constituent_ticker, sector_id)
values ("All Asia Asset Cp","AAA",
(select id from sector where sector_name = "General Financial Sector"))
答案 2 :(得分:0)
您使用的方式不是插入的方式 使用 executeUpdate()
//Initialize insertValues
insertValues = connect.prepareStatement(sql);
//Attempt to add the values into the database
try {
insertValues.executeUpdate();
} catch (Exception e) {
Log.e(CLASS_NAME, "createConstituent ", e);
}
答案 3 :(得分:0)
未知列问题似乎已通过使用单引号包围列名来解决,因此该行现在显示为:
INSERT into constituent (constituent_name, constituent_ticker, sector_id) values ("All Asia Asset Cp","AAA", (select 'id' from sector where sector_name = "General Financial Sector"))
答案 4 :(得分:0)
对不起大家。
未知列是因为应用程序指向没有该列的正确数据库,我试图通过PHPMyAdmin手动插入到具有该列的错误数据库中。
我是个白痴。谢谢。