Click here to Skip to main content
15,889,833 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
I have json file Users.json and I want read json object from file and store in to database one by one.
how to delete json object when it stored in database. when object not save in database then it not delete from file.
i have no idea about delete json object.


C#
using (FileStream fs = new FileStream("user.json", FileMode.Open, FileAccess.Read))
                    using (StreamReader sr = new StreamReader(fs))
                    using (JsonTextReader reader = new JsonTextReader(sr))
                    {
                        while (reader.Read())
                        {
                            if (reader.TokenType == JsonToken.StartObject)
                            {
                                // Load each object from the stream and do something with it
                                JObject obj = JObject.Load(reader);
                                SqlCommand cmd = null;
		   con.Open();
                                string cb = "insert into user(userid,name) VALUES ('" + obj["userid"] + "','" + obj["name"] + "')";
                                cmd = new SqlCommand(cb);
                                cmd.Connection = con;
                                cmd.ExecuteNonQuery();
		   con.Close();
                            }
                        }
                    }
Posted
Comments
Richard Deeming 10-Jun-15 8:35am    
Your code is vulnerable to SQL Injection[^].

NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.
Christian Amado 10-Jun-15 10:13am    
What about using JSON.NET library?
Sinisa Hajnal 10-Jun-15 10:44am    
Put closing and disposing of objects in finally block so they get cleaned up even if there is an exception.

Create collection of objects that couldn't be added in the database (in catch block) and then after you're done with the file, go through and delete items not in your collection (that is, those that are saved)

Better solution would be to use a library that would allow you to interract with the objects (and file) directly.

Also, what's with all the version tags? Put your version of C# and leave it.

1 solution

Since you are using SQL Server as database, I would suggest you read this article on Achieving Transactions with a Database and File System[^] for ideas.

Depending how far down the rabbit hole you want to go, you could also check out this article on Implement Your Own Resource Manager[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900