Java 将值插入引用另一个表的MySQL表以获取外键
我现在得到了下面的查询,我想用它插入两个字符串和一个外键。但是,当我传递外键的字符串时,我希望在插入时获得该键,这样记录实际上会读为: “全亚洲资产Cp”,“AAA”,1 下面是我使用的字符串:Java 将值插入引用另一个表的MySQL表以获取外键,java,mysql,Java,Mysql,我现在得到了下面的查询,我想用它插入两个字符串和一个外键。但是,当我传递外键的字符串时,我希望在插入时获得该键,这样记录实际上会读为: “全亚洲资产Cp”,“AAA”,1 下面是我使用的字符串: String sql = "INSERT into constituent " + "(constituent_name, constituent_ticker, sector_id) values (\""+ constituent.getC
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 works中按原样运行查询
使用以下命令从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;
你能不能用id来代替sector.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"))
请尝试此查询
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"))
您的使用方式不是插入的方式 使用executeUpdate()
未知列问题似乎已通过使用单引号将列名括起来而得到解决,因此该行现在显示:
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"))
对不起大家
未知列是因为应用程序指向没有该列的正确数据库,而我正试图通过PHPMyAdmin手动插入到有该列的错误数据库中
我是个白痴
谢谢你 发布扇区表的DDL后,似乎该列不存在。顺便问一下,你确定它不是扇区id而不是扇区id吗?你试过用id而不是扇区id吗?显示你的sql字符串please@Farax. 是的,我试过了。同样的问题。请确保您的内部查询返回一个结果,如果名称字段是唯一的,或者您在内部语句末尾添加了限制1,则应该足够了。恐怕存在同样的问题。如果我也这样做,也会存在同样的问题。
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"))