java - 插入查询 - executeUpdate 返回 -1

标签 java sql-server jdbc

我正在尝试使用 jdbc conn(在 Java 中)将记录插入 SQL Server。 如果我手动将查询语句复制到 java 文件中,我就可以插入到 SQL 中。但是它不是从代码中插入的?

请帮忙,我哪里犯错了?

           PreparedStatement preparedStatement = null;

        if (conn != null) {                 
            System.out.println("Connection Successful!");             
        } 

        //Create a Statement object
        Statement sql_stmt = conn.createStatement();

         //Create a Statement object
        Statement sql_stmt_1 = conn.createStatement();

        //Result Set for Prouduct Table
        ResultSet rs  = sql_stmt.executeQuery("SELECT MAX(ID), MAX(RG_ID), MAX(WG_ID) FROM " + strDBName + ".[dbo].Product");

        if ( rs.next() ) {     
            // Retrieve the auto generated key(s).     
            intID = rs.getInt(1); 
            intRG_ID = rs.getInt(2); 
            intWG_ID = rs.getInt(3); 
        }

        for (int iCount = 0 ;iCount < arrListLevel_1_Unique.size(); iCount++)
        {

         //Result Set for Prouduct Table


        sql_stmt_1.executeUpdate("\n IF NOT EXISTS(SELECT 1 FROM " + strDBName + ".[dbo].Product WHERE [Name] NOT LIKE '" + arrListLevel_1_Unique.get(iCount) + "') "
                + "\nINSERT INTO " + strDBName + ".[dbo].Product ([Name] ,"
                + "[RG_ID],[WG_ID],[Parent_Product]) "
                + "VALUES ( '" + arrListLevel_1_Unique.get(iCount) + "',"
                + + (intWG_ID + intRowIncrement) + ", " + (intWG_ID + intRowIncrement + 1) + ", 5828)");


        intRowIncrement++ ;
        }

    rs.close();
        sql_stmt.close();
        sql_stmt_1.close();


        //Close the database connection
        conn.close();

最佳答案

第五行有两个加号+:

+ + (intWG_ID + intRowIncrement) + ...

否则,问题可能出在IF ... 语句上。您可以试试这个:

    sql_stmt_1.executeUpdate(
        " INSERT INTO " + strDBName + ".[dbo].Product ([Name] ,"
      + "[RG_ID],[WG_ID],[Parent_Product]) "
      + " SELECT '" + arrListLevel_1_Unique.get(iCount) + "',"
      + (intWG_ID + intRowIncrement) + ", "
      + (intWG_ID + intRowIncrement + 1) + ", 5828 "
      + " WHERE NOT EXISTS( SELECT 1 FROM " + strDBName
      + ".[dbo].Product WHERE [Name] LIKE '"
      + arrListLevel_1_Unique.get(iCount) + "') "
    ) ;

关于java - 插入查询 - executeUpdate 返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6733053/

相关文章:

java - C# 与 Java 的接口(interface)实现差异

java - 如何在 JFreeChart 中设置条形样式

java - 正在注册 jaxws :client as a Spring bean in Spring Boot Framework

SQL Server - 查询以检索列名和列总和

hadoop - Cognos 报告 Hive 数据源很慢?

java - 如何将自定义执行器注入(inject)到播放应用程序中?

SQL Server 相当于 MySQL 的 NOW()?

sql - 获取SQL中单词的几个字母

mysql jdbc 错误的字符串值

java - Callable 或 PreparedStatement 和事务