0

I'm writing an C# application that watch for newly created xml files, and I want to insert some of the data in these XML files to a SQL database. One file is one row in the database.

What is the best and easiest way to do this?

What I have done so far is to defined a DataTable with the columns I want from the XML. After that I use ReadXML on the DataSet. This give me a DataSet with one table and one row, and the columns I want. So far it's perfect. But I can't find a good way to ONLY insert this new DataRow into my MSSQL database. I don't have any unique ID for that row yet. Would this make it easier? I don't want to map my dataset with the database, I'm only doing an insert...

2
  • SqlConnection -> SqlCommand -> SqlParameter as a start. Then "INSERT INTO [Table] ([Field1], [Field2] ...) VALUES (@Field1Value, @Field2Value ...)". Set the parameter values and ExecuteNonQuery the SqlCommand. Commented Apr 25, 2013 at 15:03
  • if you don't have unique ID that is not problem as far as inserting data, but you might not be able to set unique column later. Commented Apr 25, 2013 at 15:04

2 Answers 2

0

You can do something like this to get the ID:

    string query = "INSERT INTO Employees (EmployeeID, Name, Phone) "+
                   "OUTPUT INSERTED.EmployeeID "+
                   "VALUES (NEWID(), 'John Kris', '99-99999')";
    Guid lastId = (Guid)command.ExecuteScalar();

The rest of the things you do sound ok for me.

Sign up to request clarification or add additional context in comments.

2 Comments

So you're saying that I can't save my DataTable directly into the database without creating my Insert statement from scratch?
As for my knowledge you will allways have to somehow map the values from one datasource (xml) to the other (db). Be it in code or your sql statement.
0

I used LINQ to SQL to solve this. I set it up somewhat like described here: LINQ to SQL. On the data context I used InsertOnSubmit.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.