Click here to Skip to main content
12,401,654 members (54,296 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C# MySQL database
Hi everyone. I am trying to insert values from text-boxes into a table named employee. There are no errors occurring when I execute the query but the values aren't being added. My code is as follows:
private void InsertEmployee()
        {
            string connectionSQL = "server=sql.byethost27.org;user id=xxxxx;password=xxxxx;database=xxxxx";
            MySqlConnection conn = new MySqlConnection(connectionSQL);
            try
            {
                conn.Open();
                MySqlCommand cmd = new MySqlCommand("INSERT INTO Employee (Name,Address,City,State, ZipCode,Phone,Cell,DOB,Email,Start) VALUES ('" + name.Text + "', '" + Address.Text + "', '" + City.Text + "', '" + State.Text + "', '" + ZipCode.Text + "', '" + Phone.Text + "', '" + datePicker1.Text + "', '" + cell.Text + "', '" +Email.Text + "', '" + Start +"')", conn);
                conn.Close();
            }
 
            catch (MySqlException ex)
            {
 
                MessageBox.Show("Can't connect to database\n" + ex.ToString());
            }
        }

Any help you can give me would be much appreciated
Many Thanks
Emma
Posted 1-Apr-13 4:59am
Updated 1-Apr-13 5:02am
v2
Comments
ThePhantomUpvoter 1-Apr-13 11:03am
   
Mostly because you are not executing your SQL-injection-attack-waiting-to-happen query.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

A couple things:

1. You never call the .ExecuteNonQuery() method to update the database.

2. You are setting yourself up for sql injection attacks. Research parameterized quereis to prevent that.
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

1. cmd.ExecuteNonQuery() ; is to be called before closing connection
2. use parameterized query other wise if user puts any , or ' or any sql query then this query will not be formed properly. Using parameter u will prevent Sql Injection attack.
3. Always close and dispose connection in finally block otherwise if there is any exception in cmd.ExecuteNonQuery() the connection will remain open .
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 4

Yeah, what they said. Plus parameters will allow you to avoid passing datePicker1 as Text and use the correct type -- you are storing it in a date aren't you?
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web01 | 2.8.160721.1 | Last Updated 1 Apr 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100