Solved

How do I use C# to pull and update into SQL continuously

Posted on 2016-09-02
3
129 Views
Last Modified: 2016-09-03
This is the part of my code that continues to break.

 
        public Entry getEntry()
        {
            //Create a new entry to hold info
            Entry entry = new Entry();
            //Using my sql connection
            using (con)
            {
                //Pull all data from my Entries table
                string oString = "SELECT * FROM Entries";
                SqlCommand oCmd = new SqlCommand(oString, con);
                //Open the connection to sql

                con.Open();
                //Using what we are pulled
                using (SqlDataReader oReader = oCmd.ExecuteReader())
                {
                    //Read through the data 
                    while (oReader.Read())
                    {
                        entry.firstName = oReader["FIRST_NAME"].ToString();
                        entry.lastName = oReader["LAST_NAME"].ToString();
                        entry.Email = oReader["EMAIL"].ToString();
                        entry.Used = oReader["USED"].ToString();
                        entry.EID = oReader["EID"].ToString();
                        //If the entry is used tell me
                        if (entry.Used == "True")
                            Console.WriteLine("USED!");
                        //if the entry is not used keep it
                        else if (entry.Used == "False")
                        {
                             //CANT GET THIS TO WORK BUT THROWS NO ERRORS
                            SqlCommand newCmd = new SqlCommand("UPDATE Entries SET USED = 'True' WHERE EMAIL = '@email'", con);
                            newCmd.Parameters.AddWithValue("@email", entry.Email);
                            break;
                        }
                    }               
                    //Close connection to sql
                    con.Close();
                }

            }
            //Return the entry that we kept
            return (entry);
        }

Open in new window


Issues: I cant get the part where I commented to work and when I try and use the method more than once I get this error...

Error msg:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: The ConnectionString property has not been initialized.
0
Comment
Question by:isames
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 36

Assisted Solution

by:Miguel Oz
Miguel Oz earned 100 total points
ID: 41782507
I think you are missing  the update execute, please replace existing else code with:
//CANT GET THIS TO WORK BUT THROWS NO ERRORS
 using (SqlCommand newCmd = new SqlCommand("UPDATE Entries SET USED = 'True' WHERE EMAIL = '@email'", con))
 {
	 newCmd.Parameters.AddWithValue("@email", entry.Email);
	 newCmd.ExecuteNonQuery();//missing code.
	 break;
 }

Open in new window


If more errors present, please post error details and exact line. Also check in SQL that all your changes are committed in your target table.
0
 
LVL 13

Accepted Solution

by:
Nakul Vachhrajani earned 400 total points
ID: 41782901
It seems that when you enter the method, you already have an open connection (the "con" object is already available and ready to accept commands). Since you are "breaking" out of the WHILE loop, the connection is closed.

When you call the method again, the connection is already closed (due to con.Close()). Because you do not have an open connection, you get the error that says the connection string has not been initialized because the code doesn't know what connection to use.

There are two approaches to fix this:
1. The code that creates the connection closes it after using the connection - in this case, the connection seems to be opened outside the method, but is being closed inside the method
2. Use an exception handling logic in the method - if an attempt to establish a connection fails, re-establish it in the catch block and then move forward
1
 

Assisted Solution

by:isames
isames earned 0 total points
ID: 41782966
@Miguel --> I figured it on by using a DataSet and the sqlDataAdapter. I think the way that I was trying it (as a command) was executing but never actually writing to the database.

@Nakul --> Thanks for the advice! I started to create the connection inside of the method I was using and everything ran smoothly (I think like you said since it closed the first one you need to let it create another connection for the next run through)
0

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question