Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果特定列在java中为空,则不从excel插入mysql_Java_Mysql_Excel - Fatal编程技术网

如果特定列在java中为空,则不从excel插入mysql

如果特定列在java中为空,则不从excel插入mysql,java,mysql,excel,Java,Mysql,Excel,我正在尝试将excel工作表数据插入mysql数据库。如果列中有数据,一切都可以工作。但如果列为null,则程序停止执行,数据不会插入 下面是我如何插入excel数据 TestApp.java public class TestApp { public static void main(String[] args) throws Exception { try { Class forName = Class.forName("com.mysql.jdbc.Driv

我正在尝试将excel工作表数据插入mysql数据库。如果列中有数据,一切都可以工作。但如果列为null,则程序停止执行,数据不会插入

下面是我如何插入excel数据

TestApp.java

    public class TestApp {
    public static void main(String[] args) throws Exception {
    try {
    Class forName = Class.forName("com.mysql.jdbc.Driver");
    Connection con = null;
    con = 
    DriverManager.getConnection("jdbc:mysql://192.168.1.13:3307/db1",
    "sachin-LH", "s123");
    con.setAutoCommit(false);
    PreparedStatement pstm = null;
    FileInputStream input = new 
    FileInputStream("C:\\Users\\lh\\Downloads\\Student Details(2009-
    13).xls");
    POIFSFileSystem fs = new POIFSFileSystem(input);
    Workbook workbook;
    workbook = WorkbookFactory.create(fs);
    Sheet sheet = workbook.getSheetAt(0);
    Row row;
    for (int i = 1; i <= sheet.getLastRowNum(); i++) {
        row = (Row) sheet.getRow(i);
        String name = row.getCell(0).getStringCellValue();
        String email = row.getCell(1).getStringCellValue();
        String sql = "INSERT INTO user
        (firstName,email) VALUES('" + name + 
      "','"+email+"')";
        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 (IOException e) {
    }
    }
    }

第二行没有电子邮件,我收到空指针异常。如果特定列不存在空值,有人能告诉我如何插入空值吗?

可能很少有这种可能性

您的DB列或数据库中可能没有空约束 您正试图访问此行上的空对象 字符串email=row.getCell1.getStringCellValue; 小型工作环境: 在访问此值之前执行空检查,如

if(null != row.getCell(1)) {
   row.getCell(1).getStringCellValue();
}

此行的NPE字符串email=row.getCell1.getStringCellValue;?是的,对于电子邮件。因为对于第二个记录,没有电子邮件两个提示。不要在互联网上发布真实密码。在PreparedStatement中定义占位符并设置其值,不要使用字符串连接。这样可以避免SQL注入,而且,不需要在实例化之前将对象初始化为null。您可以在同一行中声明和实例化。连接con=null;con=驾驶员管理器。。。。这不是代码中的唯一示例。减少行数,以便更好地阅读,以便更快地获得帮助。如何检查单元格是否为空,应将字符串email=null;事先和内部如果你应该分配它是的,你可以这样做。但也要确保优化您的代码。
if(null != row.getCell(1)) {
   row.getCell(1).getStringCellValue();
}