下面我已经附加了我的程序,从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);
}
}
}
答案 0 :(得分:4)
撇号字符与SQL中用于分隔字符串文字的单引号字符相同。撇号被认为是字符串值的结束,弄乱了解析。 (这也是SQL注入工作的一种方式。)
您已使用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();