Click here to Skip to main content
15,893,337 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
public partial class Home : System.Web.UI.Page
{
   SqlConnection con = new SqlConnection("Data Source=LENOVO-PC\\SQLEXPRESS;Initial Catalog=employee;Integrated Security=True");
   
   protected void Page_Load(object sender, EventArgs e){}
   protected void Button1_Click(object sender, EventArgs e)
   {
      con.Open();
      string s = "insert into employee values('" + TextBox1.Text + "', '" + TextBox2.Text + "', " + " '" + TextBox3.Text + "') ";
      SqlCommand comm = new SqlCommand(s, con);
      com.ExecuteNonQuery();
      con.Close();
Posted
Updated 25-Jan-13 4:29am
v2
Comments
Member 9581488 25-Jan-13 9:40am    
what is the error??
PIEBALDconsult 25-Jan-13 10:06am    
Please put all the database access code in its own class -- a Data Access Layer -- rather than in your form class.
Please use parameters rather than using concatenation to form the statement.
Please use try/finally for ExecuteNonQuery and Close.

The SqlCommand calling the ExecuteNonQuery() method only has 1 "m" while you declared it with 2.

com.ExecuteNonQuery() should be comm.ExecuteNonQuery()


Also, I would declare your SqlConnection in the same scope your other code is in.
 
Share this answer
 
v2
Your INSERT statement is missing the names of the columns. Best practice is to include the names of the columns so that your SQL statements will work should someone later add one or more columns to the database table.

INSERT INTO EMPLOYEE (col1,col2,col3) Values(val1,val2,val3);

Also, when you put values directly from a TextBox into a SQL statement, your software is vulnerable to SQL Injection attacks. Best practice is to use SQLParameter Class to pass values to a parameterized SQL statement. It also performs better than when the variable value is embedded within the SQL statement.
INSERT INTO EMPLOYEE (col1,col2,col3) Values(@valName1,@valName2,@valName3);

Read this article: Use SQL Parameters to Overcome Ad Hoc Performance Issues[^]
 
Share this answer
 
v5
Comments
PIEBALDconsult 25-Jan-13 10:01am    
"missing the names of the columns"

With some databases, e.g. SQL Server, that's allowed if you are providing values to all the columns (in order). Lazy, but allowed.
Mike Meinz 25-Jan-13 10:05am    
Thank you for your comment, PIEBALDconsult. It is allowed, as you say, but it is bad practice. When a programmer does not name the columns in the SQL statements, the software breaks when a new column is added to the database table. Best practice of naming the columns allows for adding columns to the database without breaking the software.

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900