Domanda

I have connected my local database created by sql server with my project in visual studio (C#). Now I wish to enter the data given in the text field by the user in to my database. Here is what i have tried to do

    private void Button_AddCustomer_Click(object sender, EventArgs e)
    {
         try
         {
             //SqlConnection objsqlconn = new SqlConnection(conn);
             SqlConnection myConnection = new SqlConnection("Data Source=SHIRWANIPC;" + 
"Initial Catalog=TEST DATABASE;" + "Integrated Security=True");
             myConnection.Open();
             SqlCommand objcmd = new SqlCommand("INSERT INTO 
Customer(PhoneNumber,MobileNumber,Address) VALUES (a, b, c)", myConnection);
             objcmd.ExecuteNonQuery();
         }
         catch(SqlException ex)
         {
              MessageBox.Show(ex.ToString());
         }
     }

It throws an exception saying that invalid column name a,invalid column name b,invalid column name c. Whats the problem and how do I get input from the user into my database using insert query ? I am working on visual studio C# and the local database was created by using ms sql.

È stato utile?

Soluzione

Replace

VALUES (a, b, c)

with

VALUES (' + textBox1.value + (other text area) + ')'

Check the input before the query anyway!

Ok

SqlCommand objcmd = new SqlCommand("INSERT INTO Customer(PhoneNumber,MobileNumber,Address) VALUES ('" + PhoneNumber.Text + "', '" + MobileNumber.Text + "', '" + Address.Text + "')", myConnection); 

Altri suggerimenti

You need enclose string types within single quotes.

Try This:

INSERT INTO Customer(PhoneNumber,MobileNumber,Address) VALUES ('a','b','c')

Suggestion: Your query is open to sql injection attacks please use Parameterised queries to avoid them.

Try This: Using Parameterised Queries.

    private void Button_AddCustomer_Click(object sender, EventArgs e)
    {
         try
         {
             //SqlConnection objsqlconn = new SqlConnection(conn);
             SqlConnection myConnection = new SqlConnection(
             "Data Source=SHIRWANIPC;" + "Initial Catalog=TEST DATABASE;"
                                            + "Integrated Security=True");
             myConnection.Open();
             SqlCommand objcmd = new SqlCommand("INSERT INTO 
                   Customer(PhoneNumber,MobileNumber,Address) VALUES   
                  (@phonenumber,@mobilenumber,@address)", myConnection);
            objcmd.Parameters.AddWithValue("@phonenumber",TextBox1.Text);
            objcmd.Parameters.AddWithValue("@mobilenumber",TextBox2.Text);
            objcmd.Parameters.AddWithValue("@address",TextBox3.Text);
            objcmd.ExecuteNonQuery();
         }
         catch(SqlException ex)
         {
              MessageBox.Show(ex.ToString());
         }
     }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top