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
Solved

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

Posted on 2016-09-02
3
112 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
3 Comments
 
LVL 35

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

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

861 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