简体   繁体   中英

How to save file path to sql database

I am developing an application where I have to open documents from the application. I have to save the path of the file to the sql database. The column in sql to which file path is inserted is of type VARCHAR(255).

If the path of a file is C:\\Users\\UPS21120\\Downloads\\doc1.pdf ,it being saved in the database as as C:UsersUPS21120Downloadsdoc1.pdf (where are the backslashes in the saved path?).

When i retrieve this path to open the file doc1.pdf , I am getting an exception which says that doc1 does not exist .Following is the code I used to save the path. Please help.

      JFileChooser fc = new JFileChooser(); 
      returnVal = fc.showOpenDialog(view_doc.this);
      File file1=fc.getSelectedFile();

      if (returnVal == JFileChooser.APPROVE_OPTION) {
      String str = "INSERT INTO document(doc_path) VALUES ('"+file+"')";
                  // open connection..execute query etc--works fine

      }

You have to escape the value you want to insert before you insert it in the database. Or you can use prepared statements that will do that for you.

See also: Java - escape string to prevent SQL injection

to escape strings in java

http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/StringEscapeUtils.html

Escapes the characters in a String using Java String rules. ... Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

Simplest solution is use / instead of \\ in path . Then you can insert path string easily in to database. There will be no error. Also java can use path with /

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM