Solved

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

Posted on 2016-09-02
3
86 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 11

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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how the fundamental information of how to create a table.

706 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now