0

如果不存在,我如何手动插入值...我尝试了以下代码,但它产生错误。如果表中不存在,我如何插入值

 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);

它会产生一个错误,例如

 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)
4

3 回答 3

1
 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')";
于 2013-07-28T17:14:05.500 回答
0

MySQL(以及任何其他 SQL 实现)不支持查询IF NOT EXISTSINSERT

您的INSERT查询必须是

"INSERT IGNORE INTO admin (id,user_name,password,isAdmin,memo) VALUES (1,'admin','admin',1,'memo')"
于 2013-07-28T17:12:24.260 回答
0

您想要的可能是INSERT ... ON DUPLICATE KEY UPDATEINSERT IGNORE...

如果检测到重复插入,前者将更新现有行,而后者只会丢弃重复插入。

在这两种情况下,您都必须在要检查重复项的列上创建一个 UNIQUE 约束。如果违反了 UNIQUE,则调用备用函数。

于 2013-07-28T17:14:03.717 回答