下面我附上了我的程序,从 excel 导入到 mysql 时一切都对我来说很好,除了文本例如:我使用不能,不要,它在这个撇号中不会在 mysql 中接受它的显示
package importdata;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class ImportData {
/**
* @param args
*/
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/ExcelInfo","root","root");
con.setAutoCommit(false);
PreparedStatement pstm = null ;
FileInputStream input = new FileInputStream("D://check.xls");
POIFSFileSystem fs = new POIFSFileSystem( input );
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
// XSSFWorkbook wb = new XSSFWorkbook(input);
//XSSFSheet sheet = wb.getSheetAt(0);
Row row;
for(int i=1; i<=sheet.getLastRowNum(); i++){
row = sheet.getRow(i);
int id = (int) row.getCell(0).getNumericCellValue();
String name = row.getCell(1).getStringCellValue();
String address = row.getCell(2).getStringCellValue();
String sql = "INSERT INTO checking VALUES('"+id+"','"+name+"','"+address+"')";
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.execute();
System.out.println("Import rows "+i);
}
con.commit();
pstm.close();
con.close();
input.close();
System.out.println("Success import excel to mysql table");
}catch(ClassNotFoundException e){
System.out.println(e);
}catch(SQLException ex){
System.out.println(ex);
}catch(IOException ioe){
System.out.println(ioe);
}
}
}
最佳答案
撇号字符与 SQL 中用于分隔字符串文字的单引号字符相同。撇号被认为是字符串值的结尾,搞乱了解析。 (这也是 SQL 注入(inject)的一种工作方式。)
您已经在使用 PreparedStatement
。利用占位符功能。这也解决了撇号是单引号的问题。
String sql = "INSERT INTO checking VALUES(?,?,?)";
pstm = con.prepareStatement(sql);
pstm.setInt(1, id);
pstm.setString(2, name);
pstm.setString(3, address);
pstm.execute();
关于java - 将 Excel 文件导入 MySQL 数据库时无法在字符串中添加撇号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33311815/