[英]Database value insertion Error
How can i manually insert values if not exist...i tried following code but it produce error.How can i insert values if not exist in the table 如果不存在,如何手动插入值...我尝试了以下代码,但会产生错误。如果表中不存在,如何插入值
String sql1 = "CREATE TABLE IF NOT EXISTS admin " +
"(id INTEGER not NULL AUTO_INCREMENT, " +
" user_name VARCHAR(255), " +
" password VARCHAR(255), " +
" isAdmin BOOLEAN NOT NULL DEFAULT '0', " +
" memo VARCHAR(255), " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql1);
String insert="INSERT INTO admin IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
stmt.executeUpdate(insert);
it produce an error like 它产生一个错误
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'mem' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
String insert="INSERT INTO admin IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
应该
String insert="INSERT IGNORE INTO admin (id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
MySQL (and any other SQL implementation as well) doesn't support IF NOT EXISTS
in INSERT
queries. MySQL(以及任何其他SQL实现)不支持
INSERT
查询中的IF NOT EXISTS
。
your INSERT
query must be 您的
INSERT
查询必须是
"INSERT IGNORE INTO admin (id,user_name,password,isAdmin,memo) VALUES (1,'admin','admin',1,'memo')"
What you want may be INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE... . 您想要的可能是INSERT ...在重复键更新上或INSERT IGNORE ...。
The former will update an existing row if a duplicate insert is detected, while the latter will just throw away duplicate inserts. 如果检测到重复插入,前者将更新现有行,而后者将丢弃重复的插入。
In both cases, you'll have to create a UNIQUE constraint on the column you want to check for duplicates. 在这两种情况下,都必须在要检查重复项的列上创建UNIQUE约束。 If the UNIQUE is violated, the alternate function is invoked.
如果违反了UNIQUE,则调用备用函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.