Alex Merz Alex Merz - 1 year ago 58
SQL Question

Error when trying to save file path to database

I'm having an issue when I try to save a file path into Microsoft access DB, when I remove the image location from the below code, everything runs fine, as soon as I try to save a file path I get a syntax error...

below is the query...

string query = "INSERT INTO Company(companyName, phone, website, address, companyType, description, image) VALUES('" +
company.getName() + "','" + company.getPhone() + "','" + company.getWebsite() + "','" +
company.getAddress() + "','" + company.getType() + "','" + company.getDescription() + "','" +
company.getImage() + "')";

I know my code is open to sql injection but I will fix that at a later state, I have also tried parametrized queries to see if that would help the issue but it does not..

I've also tried replacing "\" with "/"

Any help would be appreciated as this is really annoying me...

Answer Source

Image is a reserved word in MS-Access Database Engine. You cannot use it as is in a query like yours. You need to encapsulate it between square brackets (or better change that field name to avoid similar problems in future)

....., [Image]) VALUES (.....

If you are aware of the problems caused by string concatenations then I really suggest you to switch as soon as possible to a Parameterized Query. (For example, what do you think will happen if your company.getDescription returns a value containing single quote?)

Another important advice that I feel to give is to abandon the java-like attitude to return properties of a class using get/set prefixed methods. One of the most distinguished feature of C# are properties. Use them.

public class Company
    public string Description {get;set;}
    public string Phone {get;set;}
    .... and so on...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download