Facebook   Twitter    YouTube    RSS Feed    Android App    iPhone and iPad App     BlackBerry App    
Subscribe to Newsletter



Page 1 of 2 1 2 LastLast
Results 1 to 15 of 20

Thread: C# Help Needed

  1. #1

    Question C# Help Needed

    I am quite new with C#, i have decided to go from PHP to Software Development and has thus far been studying a whole lot of books and tutorials. But this code down here is giving me trouble, please note this is a very basic operation I'm trying to just understand how things work...

    Any help would be appreciated.

    The following Code does nothing, it does not INSERT a new row into the database. I get the SELECT procedure to work but not this? Any Ideas?

    Thanks

    Code:
    private void button1_Click(object sender, EventArgs e)
            {
                string FirstName;
                string LastName;
                string Country;
    
                FirstName = Convert.ToString(textBox1.Text);
                LastName = Convert.ToString(textBox2.Text);
                Country = Convert.ToString(textBox3.Text);
    
                //GREATE CONNECTION TO DATABASE
                SqlConnection myConnection = new SqlConnection("Data Source=.\\SQLExpress;AttachDbFilename=|DataDirectory|\\DataBaseAccessDb.mdf;Integrated Security=True;User Instance=True;");
                
    
                SqlCommand myCommand = myConnection.CreateCommand();
                myCommand.CommandType = CommandType.Text;
                myCommand.CommandText = "INSERT INTO Users (FirstName, LastName, Country) VALUES (@FirstName, @LastName, @Country)";
                myCommand.Parameters.AddWithValue("@FirstName", FirstName);
                myCommand.Parameters.AddWithValue("@LastName", LastName);
                myCommand.Parameters.AddWithValue("@Country", Country);
                try
                {
                    myConnection.Open();
                    myCommand.ExecuteNonQuery();
    
                }
                catch (Exception ex)
                {
                    richTextBox1.Text = "There was an Error: " + Convert.ToString(ex);
                    throw;
                }
                myConnection.Close();
                
            }

  2. #2

    Default

    I think I see your problem - you've done nearly everything except actually make the connection.

    I'm not a c# guru but I know my way around most of it.

    Looking at one of my small projects with a database I have this which you are missing:
    MySqlCommand cmd = new MySqlCommand(query, connection);

    After that you then add your values and such and then later the executenonquery() as you've been doing.

  3. #3

    Default

    Don't know offhand, but I think ...

    //CREATE CONNECTION TO DATABASE
    SqlConnection myConnection = new SqlConnection("Data Source=.\\SQLExpress;AttachDbFilename=|DataDirecto ry|\\DataBaseAccessDb.mdf;Integrated Security=True;User Instance=True;");
    SqlCommand myCommand = myConnection.CreateCommand()

    is the same as your MySqlCommand cmd ... line

    What I suspect is that you are not actually firing the query. An update / insert or delete is still a query, so I would expect the line <b>myCommand.ExecuteNonQuery();</b> to be a bit different. To me the ExecuteNonQuery implies you are attempting a DDL statement or something similar, i.e. creating / dropping tables / indexes / views / truncating tables, etc, etc.

    There should be a method for Execute Query with no Result Set, though even there, there should be a way of finding out how many rows were affected, i.e. something like rowsAffected = myCommand.ExecuteInsert();

    (Quick search implies it is probably something like cmdqry.ExecuteScalar()) ...

    http://www.java2s.com/Tutorial/CShar...arecordrow.htm

  4. #4
    Grandmaster
    Join Date
    Oct 2007
    Location
    01000011 01010100
    Posts
    1,525

    Default

    Would be nice to post the exeption text and stack trace.

  5. #5

    Default

    Quote Originally Posted by bin3 View Post
    Don't know offhand, but I think ...

    //CREATE CONNECTION TO DATABASE
    SqlConnection myConnection = new SqlConnection("Data Source=.\\SQLExpress;AttachDbFilename=|DataDirecto ry|\\DataBaseAccessDb.mdf;Integrated Security=True;User Instance=True;");
    SqlCommand myCommand = myConnection.CreateCommand()

    is the same as your MySqlCommand cmd ... line

    What I suspect is that you are not actually firing the query. An update / insert or delete is still a query, so I would expect the line <b>myCommand.ExecuteNonQuery();</b> to be a bit different. To me the ExecuteNonQuery implies you are attempting a DDL statement or something similar, i.e. creating / dropping tables / indexes / views / truncating tables, etc, etc.

    There should be a method for Execute Query with no Result Set, though even there, there should be a way of finding out how many rows were affected, i.e. something like rowsAffected = myCommand.ExecuteInsert();

    (Quick search implies it is probably something like cmdqry.ExecuteScalar()) ...

    http://www.java2s.com/Tutorial/CShar...arecordrow.htm
    ExecuteNonQuery() is used for non-SELECT queries (it returns the number of results affected). ExecuteScalar() is used to return a single result (such as the result of a sum or count query).
    Last edited by thomeval; 19-05-2011 at 05:37 PM.

  6. #6
    Grandmaster
    Join Date
    Oct 2007
    Location
    01000011 01010100
    Posts
    1,525

    Default

    Also, this

    Code:
    catch (Exception ex)
    {
       richTextBox1.Text = "There was an Error: " + Convert.ToString(ex);
       throw;
    }
    should be

    Code:
    catch (Exception ex)
    {
       richTextBox1.Text = "There was an Error: " + ex.ToString();
       throw;
    }
    Although equivalent, using Convert.ToString() to invoke Exception.ToString() is bad form.

  7. #7
    Grandmaster
    Join Date
    Oct 2007
    Location
    01000011 01010100
    Posts
    1,525

    Default

    Quote Originally Posted by thomeval View Post
    ExecuteNonQuery() is used for queries that don't return results (such as rows or a number). ExecuteScalar() is used to return a single result (such as the number of rows affected by a query).
    From MSDN:

    You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.
    http://msdn.microsoft.com/en-us/libr...enonquery.aspx

  8. #8
    Grandmaster
    Join Date
    Oct 2007
    Location
    01000011 01010100
    Posts
    1,525

    Default

    Something else: by rethrowing the exception in the catch block you are also preventing this code from executing:

    Code:
    myConnection.Close();
    So maybe there other SqlConnection instances holding locks on the database (unless you restarted the application, in which case the connections might've been closed for you) but more information from the exception would help identifying this. This is where using statements come in handy:

    Code:
    using (SqlConnection myConnection = new SqlConnection("Data Source=.\\SQLExpress;AttachDbFilename=|DataDirectory|\\DataBaseAccessDb.mdf;Integrated Security=True;User Instance=True;"))
    {
       SqlCommand myCommand = myConnection.CreateCommand();
       ...
    }
    Not necessary to include the myConnection.Close().

  9. #9

    Default

    The thing is when i run the code, i do not get any exceptions, its as if the code runs trough everything correctly and then closes the connection. When i however check my Database Explorer, no new rows have been added. :/

    Thanks for all the input guys!

  10. #10

    Default

    Quote Originally Posted by Aquilla View Post
    The thing is when i run the code, i do not get any exceptions, its as if the code runs trough everything correctly and then closes the connection. When i however check my Database Explorer, no new rows have been added. :/

    Thanks for all the input guys!
    Are you refreshing the data when you check with the Database Explorer?

    One other thing worth checking is the result from ExecuteNonQuery(). The result should be 1, if the row was added successfully.

    Code:
    ...
    int rowsAffected = myCommand.ExecuteNonQuery();
    richTextBox1.Text = rowsAffected + " rows were affected.";
    ...

  11. #11

    Default

    Quote Originally Posted by thomeval View Post
    Are you refreshing the data when you check with the Database Explorer?

    One other thing worth checking is the result from ExecuteNonQuery(). The result should be 1, if the row was added successfully.

    Code:
    ...
    int rowsAffected = myCommand.ExecuteNonQuery();
    richTextBox1.Text = rowsAffected + " rows were affected.";
    ...
    I get 1 Row was affected. I have refreshed the data in the database Explorer and still it shows nothing :/

    (Can it be possible that my SQL Server Express is not functioning as it should)...?

  12. #12

    Default

    I copied and pasted your code into a new VS solution. Worked for me. Data successfully saved into the db.

    Only change I made was hardcoding the firstname, lastname and country.

  13. #13

    Default

    Try running your SELECT statement again, and see if it shows. Your data explorer might be having a funny moment. Also, do you have any rules set on the database.

    Not a C# coder, but I don't understand this
    FirstName = Convert.ToString(textBox1.Text);
    LastName = Convert.ToString(textBox2.Text);
    Country = Convert.ToString(textBox3.Text);
    Why convert a String to a String. Surely textBox1.Text is already in the String format, so why call a toString on it.
    I don't say much, but if I do say something, it pays to listen.

  14. #14

    Default

    Save yourself the effort and use a decent ORM tool.

    Subsonic I used for many years and is excellent.

    NHibernate I started using this year (Jan) and am enjoying it. Way more complex than Subsonic too configure, bit also more powerful and feature rich.

    Since .NET 4 I moved from Subsonic to Entity Framework 4. My preferred ORM tool.

    Sent from my HTC Desire HD using Tapatalk

  15. #15
    Grandmaster
    Join Date
    Jul 2007
    Location
    Bryanston
    Posts
    4,728

    Default

    Are you sure you are refreshing the same table. You might be connected to a different instance. It happens to all of us.
    i7 2600 | Asus P8H67-M (Rev B3) | Corsair TX650 | CM Scout | Mushkin Silverline BBR3 1333 -2X4GB | DeepCool Tiger Shark | 1TB Samsung | LG DVD-Writer

Page 1 of 2 1 2 LastLast

Bookmarks

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •