Pau
Pau

Reputation: 61

insert data if not exist in MySql C#

I already found the MySQL query that I want to use

INSERT INTO tbl_time_in (studentID, studentDAY, studentDATE, studentTIME_IN, temp_schedule_ID)
SELECT *  
FROM (SELECT 'rupert', 'Tuesday', 'June 29, 2016' ,'23:20', '59') AS tmp
WHERE NOT EXISTS (SELECT studentID 
                  FROM tbl_time_in 
                  WHERE studentID = 'rupert' and studentDATE = 'June 29, 2016' and temp_schedule_ID = '59')

but I also want to know how could I implement this in C# correctly.

I tried to use ExecuteNonQuery and ExecuteReader but it always gives an empty result.

Upvotes: 0

Views: 605

Answers (2)

well, you can implement this in if else statement, using a integer counter to check is the data exists or not, 1st fire the count statement and store the result in an integer, 2nd compare the the result with a 0 value - if result > 0 then the data exists in the database, else (it means result = 0) do insert Query

Upvotes: 0

eyeshield21
eyeshield21

Reputation: 186

In MySQL database you can use the ON DUPLICATE KEY UPDATE function this will lessen using of sub query. Check this link for further references.

Upvotes: 1

Related Questions