简体   繁体   English

如何将文件路径保存到sql数据库

[英]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. 我必须将文件的路径保存到sql数据库。 The column in sql to which file path is inserted is of type VARCHAR(255). 插入文件路径的sql中的列的类型为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?). 如果文件的路径是C:\\Users\\UPS21120\\Downloads\\doc1.pdf ,它将像C:UsersUPS21120Downloadsdoc1.pdf一样保存在数据库中(保存路径中的反斜杠在哪里?)。

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. 当我检索此路径以打开文件doc1.pdf我收到一个异常,说明doc1不存在。以下是我用来保存路径的代码。 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 另请参阅: Java - 用于防止SQL注入的转义字符串

to escape strings in java 在java中转义字符串

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

Escapes the characters in a String using Java String rules. 使用Java String规则转义String中的字符。 ... Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.) ...正确处理引号和控制字符(制表符,反斜杠,cr,ff等)

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 / java也可以使用带/路径

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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