How to Ignore SQL Error? - C#
I am making an insert on a unique column and the system is returning an error saying I can't insert duplicate rows. How can I ignore this error in C#?
Edit Without using try/catch
See this question for why开发者_JAVA技巧 I want to ignore the error.
Use:
try {
...sql statement execution...
} catch (SqlException ex) {
..do stuff here...
}
Use Try/Catch and on the catch do nothing.
Of course this means that the record won't be inserted, nor does it resolve the underlying problem as @recursive mentions but it would ignore the error.
If you want to insert a new row then get rid of the property value(s) that cause this to happen like an Id field or something.
Edit
If it's a hit count then you want to do an update query which i think is where you are coming from. You don't want to do a check and then either an insert / update right?
I think you might be better off using a data repository and keeping the objects in memory. if there is an id assigned to the object then you do an update on the counter, if not then an insert and you store the id with the object.
What about something like Google Analytics to check for hit counts on pages? Lot's easier, mostly free and nearly no code. is that something that might be viable?
There really is no way w/out doing an initial select or doing a try catch...
If you're using a DB that supports stored procedures, you could greatly reduce the overhead of an initial by doing the select in the stored proc and then only inserting if there are no records.
There was also a recommendation on the article you linked to that may be worth trying where you write your insert with a where clause that may work. I'm not sure if the syntax is quite right, but may be worth a shot.
Insert TableName ([column list])
Select Distinct @PK, @valueA, @ValueB, etc. -- list all values to be inserted
From TableName
Where Not Exists
(Select * From TableName
Where PK == @PK)
If you want to ignore it, catch a SqlException and swallow it...
try
{
// code that calls the database insert
}
catch(SqlException) { /* swallow */ }
If you can switch to using a stored proc, then simply nest the insert inside of a conditional block, which checks for dupes first...
If Not Exists (Select * From Table
Where PK = @PkValue)
Insert Table (ColNames here)
Values(input parameters here, including PKvalue)
Use a stored proc for this in the following way. Note that the error_number()
is from a defined error - when its inserting a duplicate with unique keys, or a PK constraint. Google if you want more details about the specific numbers
BEGIN TRY
insert into table values(x,y,x)
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627 OR ERROR_NUMBER() = 2601
-- this is a duplicate so just do nothing
ELSE
RAISERROR ('Error with Insert', -- Message text.
16, -- Severity.
1 -- State.
);
END CATCH
精彩评论