Bram
Bram

Reputation: 3264

JSON to INSERT SQL

I've been looking everywhere, can't seem to find a solution. I have a very long string in a textfile. It's already in a Json format i.e.

[{"column":"data", "anothercolumn":"data"}, {"column":"data", "anothercolumn": "data"}]

I want to convert this to an INSERT MS SQL statement using C#. Is there any way to do this? I can't figure it out myself using DeserializeObject or DataSets and DataTables. Help is much appreciated.

Upvotes: 0

Views: 878

Answers (1)

Heinzi
Heinzi

Reputation: 172200

  1. Deserialize the JSON string into an array of dictionaries.

  2. Loop through the array.

  3. Using the dictionary keys, create an SQL statement of the form: INSERT INTO myTable (key1, key2, ...) VALUES (@key1, @key2, ...).

  4. Looping through the dictionary's key-value-pairs, add the values as parameters: AddWithValue("@" + key, value).

  5. Execute the SQL statement.

  6. Profit.

The implementation is left as an exercise.

Upvotes: 3

Related Questions