?
Solved

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

Posted on 2016-09-02
3
Medium Priority
?
137 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 400 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 14

Accepted Solution

by:
Nakul Vachhrajani earned 1600 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

Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

Question has a verified solution.

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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
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.
Suggested Courses

770 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