As some of you may of seen from my previous post I'm new to using C# to create websites (Although I have a fair bit of experience using it for Windows Forms apps). The powers that be are tempting me away from PHP but I keep failing at what I consider the basics.
Anyway, this is my issue. I am trying to create a simple entry into a SQL database. I know my connection to the DB is fine as I can reel off SELECT queries all day long but I'm having trouble with using Insert.
Heres my code:
string filename = "abc123.jpg";
SqlConnection link = new SqlConnection(//you dont need to see my data here ;));
string sqlcode = "INSERT INTO file_uploads (upload_filename VALUES ("+filename+")";
SqlCommand sql = new SqlCommand(sqlcode,link);
link.open();
sql.ExecuteNonQuery();
This results in "Invalid column name abc123.jpg" returned from the try/catch.
Any help would be appreciated. (I wish they would let me do this in PHP lol!)
Thanks,
Tripbrock
Don't know if it is a typo but the line should be:
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES ('"+filename+"')";
Notice the
)
afterupload_filename
.Also also added the single quotes around the filename.
But you probably want to use a parameterized query:
string sqlcode = "INSERT INTO file_uploads (upload_filename) VALUES (@filename)";
Then use
command.Parameters
to add the actual value.You are missing a parenthesis after the column name and the value represents a string and as such must be enclosed in quotes:
However, the correct way would be to use a parameterized query:
your SQL is bad formatted. Try this :
Where upload_filename is a name of the column
Really you should be parameterising your queries - this reduces the risk of injection attacks:
Also note the
using
statements - these make sure that the connection and command objects are disposed of.looks like you are missing a bracket:
Should be
Also, to avoid SQL injection attacks you can use the SQLCommand objects like so.
Try
You were missing a closing parentheses.