• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 151
  • Last Modified:

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

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
isames
Asked:
isames
3 Solutions
 
Miguel OzSoftware EngineerCommented:
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
 
Nakul VachhrajaniTechnical Architect, Capgemini IndiaCommented:
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
 
isamesAuthor Commented:
@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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now