我写了这个插入查询:
INSERT INTO tblUsers(FirstName, LastName, UserName, Password
, EmailId, Created_Date, typeid)
VALUES ('" + ObjUserProp.FirstName + "','" + ObjUserProp.LastName + "'
,'" + ObjUserProp.UserName + "','" + ObjUserProp.Password + "'
,'" + ObjUserProp.EmailId + "','" + ObjUserProp.Created_Date + "'
," + ObjUserProp.TypeId + ")
在那我需要检查用户名和电子邮件是否存在。如果不存在那么只有插入记录其他明智的返回false
答案 0 :(得分:0)
INSERT INTO tblUsers(FirstName, LastName, UserName, Password
, EmailId, Created_Date, typeid)
SELECT ObjUserProp.FirstName as Firstname, <<-- note the keyword SELECT
ObjUserProp.LastName as lastname,
ObjUserProp.UserName as username,
ObjUserProp.Password as password,
ObjUserProp.EmailId as emailid,
ObjUserProp.Created_Date as created_date,
ObjUserProp.TypeId as typeid
FROM DUAL
WHERE NOT EXISTS (
SELECT 1 FROM tbluser u
WHERE u.username = ObjUserProp.UserName
AND u.Emailid = ObjUserProp.EmailId)
LIMIT 1
您必须将引号和+
放回查询中,但这是一般的想法。
答案 1 :(得分:0)
两个查询有什么问题?首先,使用类似select count(id) from users where username=<username> and/or email=<email>
的内容,如果计数为0,则执行插入。
答案 2 :(得分:0)
虽然Microsoft SQL Server为SQL语句提供了IF NOT EXIST
选项,但如果您使用的是MYSQL,我建议您使用INSERT ... ON DUPLICATE KEY UPDATE
语法。
这可以通过执行以下操作在您的示例中完成:
INSERT INTO tblUsers(FirstName, LastName, UserName, Password
, EmailId, Created_Date, typeid)
VALUES ('" + ObjUserProp.FirstName + "','" + ObjUserProp.LastName + "'
,'" + ObjUserProp.UserName + "','" + ObjUserProp.Password + "'
,'" + ObjUserProp.EmailId + "','" + ObjUserProp.Created_Date + "'
," + ObjUserProp.TypeId + ") ON DUPLICATE KEY UPDATE id=id
您需要确保将emailId和UserName设置为表格中的KEY。