Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. SQL Server 2008 in C# Console Appications

SQL Server 2008 in C# Console Appications

Scheduled Pinned Locked Moved C#
databasecsharpsql-serversysadmintutorial
15 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • B Offline
    B Offline
    bigjoe11a
    wrote on last edited by
    #1

    What I'm trying to do is insert a new record into a SQL Server 2008 database file. So far the samples I have fount don't work. Does any one know how to do this. Below is one of that samples I did fine. string UserConnection = Properties.Settings.Default.UsersConnectionString; SqlConnection MyConnection = new SqlConnection(UserConnection); MyConnection.Open(); String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('addr.name', 'addr.telnetaddr')"; SqlCommand MyCmd = new SqlCommand(MyString, MyConnection); MyCmd.ExecuteScalar(); MyConnection.Close(); RMDoor.WriteLn("New Entry Added"); } catch(SqlException e) { RMDoor.WriteLn(e.Message.ToString()); }

    M H 2 Replies Last reply
    0
    • B bigjoe11a

      What I'm trying to do is insert a new record into a SQL Server 2008 database file. So far the samples I have fount don't work. Does any one know how to do this. Below is one of that samples I did fine. string UserConnection = Properties.Settings.Default.UsersConnectionString; SqlConnection MyConnection = new SqlConnection(UserConnection); MyConnection.Open(); String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('addr.name', 'addr.telnetaddr')"; SqlCommand MyCmd = new SqlCommand(MyString, MyConnection); MyCmd.ExecuteScalar(); MyConnection.Close(); RMDoor.WriteLn("New Entry Added"); } catch(SqlException e) { RMDoor.WriteLn(e.Message.ToString()); }

      M Offline
      M Offline
      Mbah Dhaim
      wrote on last edited by
      #2

      bigjoe11a wrote:

      MyCmd.ExecuteScalar();

      Replace with MyCmd.ExecuteNonQuery(); hope it helps

      dhaim ing ngarso sung tulodho, ing madyo mangun karso, tut wuri handayani. "Ki Hajar Dewantoro" in the front line gave a lead, in the middle line build goodwill, in the behind give power support

      B 1 Reply Last reply
      0
      • M Mbah Dhaim

        bigjoe11a wrote:

        MyCmd.ExecuteScalar();

        Replace with MyCmd.ExecuteNonQuery(); hope it helps

        dhaim ing ngarso sung tulodho, ing madyo mangun karso, tut wuri handayani. "Ki Hajar Dewantoro" in the front line gave a lead, in the middle line build goodwill, in the behind give power support

        B Offline
        B Offline
        bigjoe11a
        wrote on last edited by
        #3

        Thanks how ever I did try that too. and for some reason. It just not inserting. Its not giving me any errors.

        1 Reply Last reply
        0
        • B bigjoe11a

          What I'm trying to do is insert a new record into a SQL Server 2008 database file. So far the samples I have fount don't work. Does any one know how to do this. Below is one of that samples I did fine. string UserConnection = Properties.Settings.Default.UsersConnectionString; SqlConnection MyConnection = new SqlConnection(UserConnection); MyConnection.Open(); String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('addr.name', 'addr.telnetaddr')"; SqlCommand MyCmd = new SqlCommand(MyString, MyConnection); MyCmd.ExecuteScalar(); MyConnection.Close(); RMDoor.WriteLn("New Entry Added"); } catch(SqlException e) { RMDoor.WriteLn(e.Message.ToString()); }

          H Offline
          H Offline
          Henry Minute
          wrote on last edited by
          #4

          The problem is caused by String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('addr.name', 'addr.telnetaddr')";, in particular the VALUES clause. By enclosing addr.name etc in the quotes they are treated as just another part of the string. Their values are not fetched and used, as you intended. What you need is a parameterized SQLcommand take a look at the example here[^] and try to adapt it for your data. Please post back if you get stuck.

          Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

          B 2 Replies Last reply
          0
          • H Henry Minute

            The problem is caused by String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('addr.name', 'addr.telnetaddr')";, in particular the VALUES clause. By enclosing addr.name etc in the quotes they are treated as just another part of the string. Their values are not fetched and used, as you intended. What you need is a parameterized SQLcommand take a look at the example here[^] and try to adapt it for your data. Please post back if you get stuck.

            Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

            B Offline
            B Offline
            bigjoe11a
            wrote on last edited by
            #5

            Well I'm stuck. Is there a sample related to what I'm doing. This isn't going to work.

            1 Reply Last reply
            0
            • H Henry Minute

              The problem is caused by String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('addr.name', 'addr.telnetaddr')";, in particular the VALUES clause. By enclosing addr.name etc in the quotes they are treated as just another part of the string. Their values are not fetched and used, as you intended. What you need is a parameterized SQLcommand take a look at the example here[^] and try to adapt it for your data. Please post back if you get stuck.

              Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

              B Offline
              B Offline
              bigjoe11a
              wrote on last edited by
              #6

              I didn't see the extra commands at the top. This is an update. I need an insert

              H 1 Reply Last reply
              0
              • B bigjoe11a

                I didn't see the extra commands at the top. This is an update. I need an insert

                H Offline
                H Offline
                Henry Minute
                wrote on last edited by
                #7

                OK. For now, try breaking the string up like this:

                String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('" + addr.name.ToString().Trim() + "', '" + addr.telnetaddr.ToString().Trim() + "')";

                Leave out the .ToString() if addr.name etc. is sure to return a string. I would leave the .Trim() there if it were me. For the future, it might bring benefits to learn about Parameterized Queries, they make things a lot easier in many cases. Good luck. :)

                Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

                B 1 Reply Last reply
                0
                • H Henry Minute

                  OK. For now, try breaking the string up like this:

                  String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('" + addr.name.ToString().Trim() + "', '" + addr.telnetaddr.ToString().Trim() + "')";

                  Leave out the .ToString() if addr.name etc. is sure to return a string. I would leave the .Trim() there if it were me. For the future, it might bring benefits to learn about Parameterized Queries, they make things a lot easier in many cases. Good luck. :)

                  Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

                  B Offline
                  B Offline
                  bigjoe11a
                  wrote on last edited by
                  #8

                  well I'm getting some errors on some of the lines. So I can't compile yet. I do know that some of of it is missing. My code is below string UserConnection = Properties.Settings.Default.UsersConnectionString; SqlConnection MyConnection = new SqlConnection(UserConnection); String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('" + addr.name.ToString().TRIM() + "', '" + addr.telnetaddr.ToString().Trim() + "')"; SqlCommand command = new SqlCommand(MyString, MyConnection); //command.Parameters.Add("@ID", SqlDbType.Int); //command.Parameters["@ID"].Value = ID; command.Parameters.Add("@Name", SqlDbType.Text); command.Parameters["@Name"].Value = addr.name; command.Parameters.Add("@telnetaddr", SqlDbType.Text); command.Parameters["@telnetaddr"].Value = addr.telnetaddr; // Use AddWithValue to assign Demographics. // SQL Server will implicitly convert strings into XML. command.Parameters.AddWithValue(commandText, ); try { MyConnection.Open(); Int32 rowsAffected = command.ExecuteNonQuery(); Console.WriteLine("RowsAffected: {0}", rowsAffected); } catch (Exception ex) { Console.WriteLine(ex.Message); } Error 1 Argument missing C:\Users\Joe\Documents\Visual Studio 2008\Projects\MyDoor\Program.cs 245 66 MyDoor Error 2 'string' does not contain a definition for 'TRIM' and no extension method 'TRIM' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) C:\Users\Joe\Documents\Visual Studio 2008\Projects\MyDoor\Program.cs 233 114 MyDoor Error 3 The name 'commandText' does not exist in the current context C:\Users\Joe\Documents\Visual Studio 2008\Projects\MyDoor\Program.cs 245 53 MyDoor What I should have ask if some one could type out the full code So I know I get every thing right.

                  H 2 Replies Last reply
                  0
                  • B bigjoe11a

                    well I'm getting some errors on some of the lines. So I can't compile yet. I do know that some of of it is missing. My code is below string UserConnection = Properties.Settings.Default.UsersConnectionString; SqlConnection MyConnection = new SqlConnection(UserConnection); String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('" + addr.name.ToString().TRIM() + "', '" + addr.telnetaddr.ToString().Trim() + "')"; SqlCommand command = new SqlCommand(MyString, MyConnection); //command.Parameters.Add("@ID", SqlDbType.Int); //command.Parameters["@ID"].Value = ID; command.Parameters.Add("@Name", SqlDbType.Text); command.Parameters["@Name"].Value = addr.name; command.Parameters.Add("@telnetaddr", SqlDbType.Text); command.Parameters["@telnetaddr"].Value = addr.telnetaddr; // Use AddWithValue to assign Demographics. // SQL Server will implicitly convert strings into XML. command.Parameters.AddWithValue(commandText, ); try { MyConnection.Open(); Int32 rowsAffected = command.ExecuteNonQuery(); Console.WriteLine("RowsAffected: {0}", rowsAffected); } catch (Exception ex) { Console.WriteLine(ex.Message); } Error 1 Argument missing C:\Users\Joe\Documents\Visual Studio 2008\Projects\MyDoor\Program.cs 245 66 MyDoor Error 2 'string' does not contain a definition for 'TRIM' and no extension method 'TRIM' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) C:\Users\Joe\Documents\Visual Studio 2008\Projects\MyDoor\Program.cs 233 114 MyDoor Error 3 The name 'commandText' does not exist in the current context C:\Users\Joe\Documents\Visual Studio 2008\Projects\MyDoor\Program.cs 245 53 MyDoor What I should have ask if some one could type out the full code So I know I get every thing right.

                    H Offline
                    H Offline
                    Henry Minute
                    wrote on last edited by
                    #9

                    Error 2 is my fault I put it in uppercase, it should be Trim(). :-O Have a try with that change while I look at the others.

                    Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

                    1 Reply Last reply
                    0
                    • B bigjoe11a

                      well I'm getting some errors on some of the lines. So I can't compile yet. I do know that some of of it is missing. My code is below string UserConnection = Properties.Settings.Default.UsersConnectionString; SqlConnection MyConnection = new SqlConnection(UserConnection); String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('" + addr.name.ToString().TRIM() + "', '" + addr.telnetaddr.ToString().Trim() + "')"; SqlCommand command = new SqlCommand(MyString, MyConnection); //command.Parameters.Add("@ID", SqlDbType.Int); //command.Parameters["@ID"].Value = ID; command.Parameters.Add("@Name", SqlDbType.Text); command.Parameters["@Name"].Value = addr.name; command.Parameters.Add("@telnetaddr", SqlDbType.Text); command.Parameters["@telnetaddr"].Value = addr.telnetaddr; // Use AddWithValue to assign Demographics. // SQL Server will implicitly convert strings into XML. command.Parameters.AddWithValue(commandText, ); try { MyConnection.Open(); Int32 rowsAffected = command.ExecuteNonQuery(); Console.WriteLine("RowsAffected: {0}", rowsAffected); } catch (Exception ex) { Console.WriteLine(ex.Message); } Error 1 Argument missing C:\Users\Joe\Documents\Visual Studio 2008\Projects\MyDoor\Program.cs 245 66 MyDoor Error 2 'string' does not contain a definition for 'TRIM' and no extension method 'TRIM' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) C:\Users\Joe\Documents\Visual Studio 2008\Projects\MyDoor\Program.cs 233 114 MyDoor Error 3 The name 'commandText' does not exist in the current context C:\Users\Joe\Documents\Visual Studio 2008\Projects\MyDoor\Program.cs 245 53 MyDoor What I should have ask if some one could type out the full code So I know I get every thing right.

                      H Offline
                      H Offline
                      Henry Minute
                      wrote on last edited by
                      #10

                      None of this is needed now that you are no longer trying Parameterized stuff.

                      //command.Parameters.Add("@ID", SqlDbType.Int);
                      //command.Parameters["@ID"].Value = ID;
                      command.Parameters.Add("@Name", SqlDbType.Text);
                      command.Parameters["@Name"].Value = addr.name;
                      command.Parameters.Add("@telnetaddr", SqlDbType.Text);
                      command.Parameters["@telnetaddr"].Value = addr.telnetaddr;

                      // Use AddWithValue to assign Demographics.
                      // SQL Server will implicitly convert strings into XML.
                      command.Parameters.AddWithValue(commandText, );

                      either delete those lines or preferably just comment them out until you have the thing working. Error 3 is caused by Error 2, so should be alright now. The stuff about MyDoor, I cannot help with, although I remember seeing it in one of your previous posts.

                      Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

                      B 1 Reply Last reply
                      0
                      • H Henry Minute

                        None of this is needed now that you are no longer trying Parameterized stuff.

                        //command.Parameters.Add("@ID", SqlDbType.Int);
                        //command.Parameters["@ID"].Value = ID;
                        command.Parameters.Add("@Name", SqlDbType.Text);
                        command.Parameters["@Name"].Value = addr.name;
                        command.Parameters.Add("@telnetaddr", SqlDbType.Text);
                        command.Parameters["@telnetaddr"].Value = addr.telnetaddr;

                        // Use AddWithValue to assign Demographics.
                        // SQL Server will implicitly convert strings into XML.
                        command.Parameters.AddWithValue(commandText, );

                        either delete those lines or preferably just comment them out until you have the thing working. Error 3 is caused by Error 2, so should be alright now. The stuff about MyDoor, I cannot help with, although I remember seeing it in one of your previous posts.

                        Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

                        B Offline
                        B Offline
                        bigjoe11a
                        wrote on last edited by
                        #11

                        Well this is what why code likes like now. I'm just going to add the rest of the code. I didn't think it would help. Here it is. Don't worry about the RMDoor. Its just an add on library that I added. //////////////////////////////////// public static void add() { RMDoor.ClrScr(); Person addr = new Person(); RMDoor.Write("Enter Name : "); addr.name = RMDoor.ReadLn(); RMDoor.Write("Address : "); addr.telnetaddr = RMDoor.ReadLn(); RMDoor.ClrScr(); RMDoor.WriteLn("BBS Name : " + addr.name); RMDoor.WriteLn("Telnet Address : " + addr.telnetaddr); RMDoor.WriteLn(); RMDoor.Write("Is this what you want Y/N"); string Q = RMDoor.ReadLn(); Q = Q.ToUpper(); savelog("User has just added an entry"); if (Q == "Y") { string UserConnection = Properties.Settings.Default.UsersConnectionString; SqlConnection MyConnection = new SqlConnection(UserConnection); String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('" + addr.name + "', '" + addr.telnetaddr + "')"; SqlCommand MyCmd = new SqlCommand(MyString, MyConnection); MyConnection.Open(); try { MyCmd.ExecuteNonQuery(); Int32 rowsAffected = MyCmd.ExecuteNonQuery(); RMDoor.WriteLn("RowsAffected: " + rowsAffected); MyConnection.Close(); } catch (SqlException ex) { RMDoor.WriteLn(ex.Message); } } else { RMDoor.WriteLn("Save Aborted"); } RMDoor.WriteLn("Press Enter to Continue"); RMDoor.WriteLn(); } I hope this helps. It just doesn't work.

                        H 1 Reply Last reply
                        0
                        • B bigjoe11a

                          Well this is what why code likes like now. I'm just going to add the rest of the code. I didn't think it would help. Here it is. Don't worry about the RMDoor. Its just an add on library that I added. //////////////////////////////////// public static void add() { RMDoor.ClrScr(); Person addr = new Person(); RMDoor.Write("Enter Name : "); addr.name = RMDoor.ReadLn(); RMDoor.Write("Address : "); addr.telnetaddr = RMDoor.ReadLn(); RMDoor.ClrScr(); RMDoor.WriteLn("BBS Name : " + addr.name); RMDoor.WriteLn("Telnet Address : " + addr.telnetaddr); RMDoor.WriteLn(); RMDoor.Write("Is this what you want Y/N"); string Q = RMDoor.ReadLn(); Q = Q.ToUpper(); savelog("User has just added an entry"); if (Q == "Y") { string UserConnection = Properties.Settings.Default.UsersConnectionString; SqlConnection MyConnection = new SqlConnection(UserConnection); String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('" + addr.name + "', '" + addr.telnetaddr + "')"; SqlCommand MyCmd = new SqlCommand(MyString, MyConnection); MyConnection.Open(); try { MyCmd.ExecuteNonQuery(); Int32 rowsAffected = MyCmd.ExecuteNonQuery(); RMDoor.WriteLn("RowsAffected: " + rowsAffected); MyConnection.Close(); } catch (SqlException ex) { RMDoor.WriteLn(ex.Message); } } else { RMDoor.WriteLn("Save Aborted"); } RMDoor.WriteLn("Press Enter to Continue"); RMDoor.WriteLn(); } I hope this helps. It just doesn't work.

                          H Offline
                          H Offline
                          Henry Minute
                          wrote on last edited by
                          #12

                          Apart from the fact that you execute the command twice:

                          MyCmd.ExecuteNonQuery();
                          Int32 rowsAffected = MyCmd.ExecuteNonQuery();

                          I could not see anything wrong with the code, as it is. So I copied and pasted it into a project. To get it to compile on my machine I changed all your calls to RMDoor.whatever to Console.whatever and commented out the savelog line. I created a new database, added a table called UserData with two columns Name and telnetaddr both nvarchar(50). In the project I created a new DataSource ConsoleUsersTestDataSource from the database above, and ran the project. Because the command executes twice, it added two new records, with identical data. Just so that you can see that my code is essentially identical to yours, here it is:

                          class Program
                          {
                          	static void Main(string\[\] args)
                          	{
                          		add();
                          	}
                          
                          	public static void add()
                          	{
                          		Console.Clear();
                          
                          		Person addr = new Person();
                          
                          		Console.Write("Enter Name : ");
                          		addr.name = Console.ReadLine();
                          
                          
                          		Console.Write("Address : ");
                          		addr.telnetaddr = Console.ReadLine();
                          
                          		Console.Clear();
                          
                          		Console.WriteLine("BBS Name : " + addr.name);
                          		Console.WriteLine("Telnet Address : " + addr.telnetaddr);
                          		Console.WriteLine();
                          
                          		Console.Write("Is this what you want Y/N");
                          		string Q = Console.ReadLine();
                          		Q = Q.ToUpper();
                          		//savelog("User has just added an entry");
                          		if (Q == "Y")
                          		{
                          			string UserConnection = Properties.Settings.Default.ConsoleUsersTestConnectionString;
                          			SqlConnection MyConnection = new SqlConnection(UserConnection);
                          
                          			String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('" + addr.name + "', '" + addr.telnetaddr + "')";
                          			SqlCommand MyCmd = new SqlCommand(MyString, MyConnection);
                          
                          			MyConnection.Open();
                          			try
                          			{
                          				MyCmd.ExecuteNonQuery();
                          				Int32 rowsAffected = MyCmd.ExecuteNonQuery();
                          				Console.WriteLine("RowsAffected: " + rowsAffected);
                          				MyConnection.Close();
                          			}
                          			catch (SqlException ex)
                          			{
                          				Console.WriteLine(ex.Message);
                          			}
                          
                          
                          		}
                          		else
                          		{
                          			Console.WriteLine("Save Aborted");
                          
                          		}
                          
                          		Console.WriteLine("Press Enter to Continue");
                          		Console.WriteLine();
                          
                          	}
                          }
                          

                          I can only suggest that you try cleaning your solution (Build | Clean Solution, just in case you don't know) and then rebuild it. If it doesn't work then, I can only assume that there is something wrong with your database; or you have duplicate da

                          B 1 Reply Last reply
                          0
                          • H Henry Minute

                            Apart from the fact that you execute the command twice:

                            MyCmd.ExecuteNonQuery();
                            Int32 rowsAffected = MyCmd.ExecuteNonQuery();

                            I could not see anything wrong with the code, as it is. So I copied and pasted it into a project. To get it to compile on my machine I changed all your calls to RMDoor.whatever to Console.whatever and commented out the savelog line. I created a new database, added a table called UserData with two columns Name and telnetaddr both nvarchar(50). In the project I created a new DataSource ConsoleUsersTestDataSource from the database above, and ran the project. Because the command executes twice, it added two new records, with identical data. Just so that you can see that my code is essentially identical to yours, here it is:

                            class Program
                            {
                            	static void Main(string\[\] args)
                            	{
                            		add();
                            	}
                            
                            	public static void add()
                            	{
                            		Console.Clear();
                            
                            		Person addr = new Person();
                            
                            		Console.Write("Enter Name : ");
                            		addr.name = Console.ReadLine();
                            
                            
                            		Console.Write("Address : ");
                            		addr.telnetaddr = Console.ReadLine();
                            
                            		Console.Clear();
                            
                            		Console.WriteLine("BBS Name : " + addr.name);
                            		Console.WriteLine("Telnet Address : " + addr.telnetaddr);
                            		Console.WriteLine();
                            
                            		Console.Write("Is this what you want Y/N");
                            		string Q = Console.ReadLine();
                            		Q = Q.ToUpper();
                            		//savelog("User has just added an entry");
                            		if (Q == "Y")
                            		{
                            			string UserConnection = Properties.Settings.Default.ConsoleUsersTestConnectionString;
                            			SqlConnection MyConnection = new SqlConnection(UserConnection);
                            
                            			String MyString = @"INSERT INTO UserData (Name, telnetaddr) VALUES('" + addr.name + "', '" + addr.telnetaddr + "')";
                            			SqlCommand MyCmd = new SqlCommand(MyString, MyConnection);
                            
                            			MyConnection.Open();
                            			try
                            			{
                            				MyCmd.ExecuteNonQuery();
                            				Int32 rowsAffected = MyCmd.ExecuteNonQuery();
                            				Console.WriteLine("RowsAffected: " + rowsAffected);
                            				MyConnection.Close();
                            			}
                            			catch (SqlException ex)
                            			{
                            				Console.WriteLine(ex.Message);
                            			}
                            
                            
                            		}
                            		else
                            		{
                            			Console.WriteLine("Save Aborted");
                            
                            		}
                            
                            		Console.WriteLine("Press Enter to Continue");
                            		Console.WriteLine();
                            
                            	}
                            }
                            

                            I can only suggest that you try cleaning your solution (Build | Clean Solution, just in case you don't know) and then rebuild it. If it doesn't work then, I can only assume that there is something wrong with your database; or you have duplicate da

                            B Offline
                            B Offline
                            bigjoe11a
                            wrote on last edited by
                            #13

                            Thanks. That's works now. It turned out to be the table name was wrong. That's why. It Shows as UserData and it should be UaersData. What I did was I went back and check my lines again making sure they were all spelled right and so. I changed so many times. I forgot to change it back. I can't under stand why it didn't throw an error. Ok, now. Now how about a search. How can I setup a search. Using the same code or is that not the same. string sname = "Tom Cat"; So how would I search for this name and if it finds it, it displays the record. If not it throws an error.

                            H 1 Reply Last reply
                            0
                            • B bigjoe11a

                              Thanks. That's works now. It turned out to be the table name was wrong. That's why. It Shows as UserData and it should be UaersData. What I did was I went back and check my lines again making sure they were all spelled right and so. I changed so many times. I forgot to change it back. I can't under stand why it didn't throw an error. Ok, now. Now how about a search. How can I setup a search. Using the same code or is that not the same. string sname = "Tom Cat"; So how would I search for this name and if it finds it, it displays the record. If not it throws an error.

                              H Offline
                              H Offline
                              Henry Minute
                              wrote on last edited by
                              #14

                              For that you will need to use a SELECT Command, which would look something like:

                              SELECT * FROM dbo.UaersData WHERE Name = @userName

                              ******************************** Note ************************** This is only approximate. and it uses a parameter (the @userName) However instead of that you can do as you have done for the INSERT and break the string into bits, a bit like:

                              string commandString = "SELECT * FROM dbo.UaersData WHERE Name = '" + theVariableHoldingTheNameFromTheConsole + "'";

                              In order to use it efficiently however you really should use the Prameterized methodology. In the mean time take a look at this[^], scroll down till you reach the Executing SQL Statements that Return Rows Using a Command Object section. This is very similar to the method you have been using. You will then need to research the SqlDataReader object to find out how to get the data from the reader As this is really basic stuff, I think you will be better off if you do some reading in the MSDN Documentation, and by googling. If you have any further questions, I would suggest that you start a new thread, as I will be away from my PC for a few hours.

                              Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

                              B 1 Reply Last reply
                              0
                              • H Henry Minute

                                For that you will need to use a SELECT Command, which would look something like:

                                SELECT * FROM dbo.UaersData WHERE Name = @userName

                                ******************************** Note ************************** This is only approximate. and it uses a parameter (the @userName) However instead of that you can do as you have done for the INSERT and break the string into bits, a bit like:

                                string commandString = "SELECT * FROM dbo.UaersData WHERE Name = '" + theVariableHoldingTheNameFromTheConsole + "'";

                                In order to use it efficiently however you really should use the Prameterized methodology. In the mean time take a look at this[^], scroll down till you reach the Executing SQL Statements that Return Rows Using a Command Object section. This is very similar to the method you have been using. You will then need to research the SqlDataReader object to find out how to get the data from the reader As this is really basic stuff, I think you will be better off if you do some reading in the MSDN Documentation, and by googling. If you have any further questions, I would suggest that you start a new thread, as I will be away from my PC for a few hours.

                                Henry Minute Do not read medical books! You could die of a misprint. - Mark Twain Girl: (staring) "Why do you need an icy cucumber?" “I want to report a fraud. The government is lying to us all.”

                                B Offline
                                B Offline
                                bigjoe11a
                                wrote on last edited by
                                #15

                                Well I wanted to tell you too. That when I added the new record. It added it. But is didn't save it to the database. When I added the record. And I when to view all the records. The 3rd and new record was there. How ever when I closed the application and look in the database explorer. to view the records. The 3rd record was missing. Looks like it never got added to the database file. And all so I have been doing searches for all this at google and I go throw 100's of pages and still can't find what I'm looking for. Thats why I desided to post.

                                1 Reply Last reply
                                0
                                Reply
                                • Reply as topic
                                Log in to reply
                                • Oldest to Newest
                                • Newest to Oldest
                                • Most Votes


                                • Login

                                • Don't have an account? Register

                                • Login or register to search.
                                • First post
                                  Last post
                                0
                                • Categories
                                • Recent
                                • Tags
                                • Popular
                                • World
                                • Users
                                • Groups