Click here to Skip to main content
15,899,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I'm trying to insert data into a database.

This is my code:
C#
SqlCeConnection conn = new SqlCeConnection(connStr);
conn.Open();

string cmd = "INSERT INTO Log(Type,Rego) VALUES(" + typeBox.Text + "," +     regoBox.Text + ")";

SqlCeCommand writeToDB = new SqlCeCommand(cmd, conn);
writeToDB.ExecuteNonQuery();
conn.Close();


Type is an ntext column and Rego is a float. When I put DA40 in typeBox and 3.0 in regoBox I come up with this error:

The column name is not valid. [Node name (if any)=,Column name=DA40]

Am I doing something silly?
Some help would be most appreciated, thanks
Posted
Comments
Tech Code Freak 26-Sep-11 1:22am    
Apart from your question, I want to ask you what are you 'using'?
i.e. When we include 'using System.Data.SqlClient' in .Net Framework 3.5, we normally get SqlConnection, SqlCommand classes. How come you've got SqlCeConnection and SqlCeCommand classes? Sounds strange!

The problem is that you need to have single quotes around the value for Type. Using string concatenation is frowned upon when working with SQL because of SQL injection and other issues. You should get in the habit of using parameterized queries.

C#
string cmd = "INSERT INTO Log(Type, Rego) VALUES('" + typeBox.Text + "'," + regoBox.Text + ")";


Parameterized Query Version.

C#
SqlCeConnection conn = new SqlCeConnection(connStr);
conn.Open();
 
string cmd = "INSERT INTO Log(Type, Rego) VALUES(@Type, @Rego)";
 
SqlCeCommand writeToDB = new SqlCeCommand(cmd, conn);
writeToDB.Parameters.Add(new SqlCeParameter("@Type", typeBox.Text);
writeToDB.Parameters.Add(new SqlCeParameter("@Rego", regoBox.Text);
writeToDB.ExecuteNonQuery();
conn.Close();
 
Share this answer
 
Comments
Uday P.Singh 26-Sep-11 1:33am    
my 5!
You forgot to enclose the value of the type column with '(Single Quotes). Also, please note that this is not a good way to write queries. Use parameters in putting values to your SqlCommand. See here[^] for reference.
 
Share this answer
 
you have done one mistak.

C#
string cmd = "INSERT INTO Log(Type,Rego) VALUES('" + typeBox.Text + "'," + regoBox.Text + ")";


put this line into ur code.
 
Share this answer
 
v3
Comments
Spramodthapa 25-Sep-11 22:30pm    
why u guyz always make string concatination.

jus follow diz

public insert into tbluser(string name,string password)
{
sqlparameter[] param=new sqlparameter[2];
sqlparameter[0] param=new sqlparameter("@name",name);
sqlparameter[1] param=new sqlparameter("@password",password);
return connect.procedure("sp_user",param);
}
Anil Honey 206 26-Sep-11 0:54am    
good

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