【问题标题】:Insert data and if already inserted then update in sql插入数据,如果已经插入,则在 sql 中更新
【发布时间】:2016-04-06 05:30:53
【问题描述】:

我只是想将数据插入到 SQL 数据库表中,如果已经插入了一些数据,那么我想更新该数据。如何使用 Java 做到这一点。请帮助我,对于英语不好提前道歉。

【问题讨论】:

标签: java sql


【解决方案1】:

将任意字段设置为唯一标识。 例如,请考虑必须在表名**EmployeeDetails.**中输入员工详细信息。在这种情况下,employee_id 可以被认为是唯一的。

使用 SELECT 查询 select * from EmployeeDetails where employee_id="the unique keyvalue"; 如果结果集不为空,则使用 UPDATE 查询更新字段。

更新 EmployeeDetails 设置 Employee_id=?,Full_name=?, Designation=?, Email_id=?, Password=?其中 Employee_id='" + id + "'"; 如果结果集为空,则使用 INSERT 查询将值插入到表中

插入 EmployeeDetails 值(...)

【讨论】:

    【解决方案2】:
    package com.stackwork;
    
    //STEP 1. Import required packages
    import java.sql.*;
    import java.util.Scanner;
    
    public class Updation {
       // JDBC driver name and database URL
       static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
       static final String DB_URL = "jdbc:mysql://localhost/Employee";
    
       //  Database credentials
       static final String USER = "root";
       static final String PASS = "admin";
       private static Scanner sc;
    
       public static void main(String[] args) {
       Connection conn = null;
       Statement stmt = null;
       try{
          //STEP 2: Register JDBC driver
          Class.forName("com.mysql.jdbc.Driver");
          //STEP 3: Open a connection
          System.out.println("Connecting to database...");
          conn = DriverManager.getConnection(DB_URL,USER,PASS);
          //STEP 4: Execute a query
          System.out.println("Creating statement...");
          stmt = conn.createStatement();
          String sql;
          //STEP 5: Get the employee_id for whom data need to be updated/inserted
          sc = new Scanner(System.in);
          System.out.println("Enter the Employee_id for the record to be updated or inserted");
          int Emp_idvalue=sc.nextInt();
          sql = "SELECT * FROM EmployeeDetails where Emp_id="+Emp_idvalue;
          ResultSet rs = stmt.executeQuery(sql);
          if (!rs.next())
          {
              //STEP 6: If the previous details is not there ,then the details will be inserted newly
              System.out.println("Enter the name to be inserted");
              String Emp_namevalue =sc.next();
              System.out.println("Enter the address to be inserted");
              String Emp_addvalue =sc.next();
              System.out.println("Enter the role to be inserted");
              String Emp_rolevalue =sc.next();
              PreparedStatement ps = conn
                        .prepareStatement("insert into EmployeeDetails values(?,?,?,?)");
                ps.setString(2, Emp_namevalue);
                ps.setString(3, Emp_addvalue);
                ps.setString(4, Emp_rolevalue);
                ps.setInt(1, Emp_idvalue);
                ps.executeUpdate();
                System.out.println("Inserted successfully");
          }
          else
          {
            //STEP 7: If the previous details is  there ,then the details will be updated 
              System.out.println("Enter the name to be updated");
              String Emp_namevalue =sc.next();
              System.out.println("Enter the address to be updated");
              String Emp_addvalue =sc.next();
              System.out.println("Enter the role to be updated");
              String Emp_rolevalue =sc.next();
              String updateQuery = "update EmployeeDetails set Emp_id=?,Emp_name=?, Emp_address=?, Emp_role=? where Emp_id='"
                        + Emp_idvalue + "'";
                PreparedStatement ps1 = conn.prepareStatement(updateQuery);
                ps1.setString(2, Emp_namevalue);
                ps1.setString(3, Emp_addvalue);
                ps1.setString(4, Emp_rolevalue);
                ps1.setInt(1, Emp_idvalue);
                ps1.executeUpdate();    
                System.out.println("updated successfully");
    
          }
          //Clean-up environment
          rs.close();
          stmt.close();
          conn.close();
       }catch(SQLException se){
          //Handle errors for JDBC
          se.printStackTrace();
    
       }catch(Exception e){
          //Handle errors for Class.forName
          e.printStackTrace();
      }
    }
    }
    

    【讨论】:

      【解决方案3】:

      INSERT(如果新)或UPDATE(如果存在)的标准 SQL 语句称为 MERGE。

      由于您没有具体说明您要询问的是哪种 DBMS 方言,我建议您参考 Wikipedia 文章“Merge (SQL)”,该文章涵盖了大多数 DBMS 方言。总结:

      MERGE INTO tablename USING table_reference ON (condition)
      WHEN MATCHED THEN
        UPDATE SET column1 = value1 [, column2 = value2 ...]
      WHEN NOT MATCHED THEN
        INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...])
      

      数据库管理系统 Oracle 数据库、DB2、Teradata、EXASOL、CUBRID、MS SQL 和 Vectorwise 支持标准语法。有些还添加了非标准的 SQL 扩展。

      MySQL:INSERT ... ON DUPLICATE KEY UPDATE

      SQLite:INSERT OR REPLACE INTO

      PostgreSQL:INSERT INTO ... ON CONFLICT

      【讨论】:

      • 问题与 Java(JDBC.HSQL 或其他 ORM)有关。
      • @EddyBayonne 是的,您也可以从 Java 运行这些 SQL 语句。问题中没有提到 ORM,因此使用 JDBC 运行 SQL 是一个完全有效的答案。
      • 我们应该更喜欢在一个连接和语句中完成工作的策略。上面的答案最好避免多个连接开口和批量性能影响。
      【解决方案4】:

      尝试以下方式:

      示例查询

      INSERT INTO 表(id​​、name、city)VALUES(1, "ABC", "XYZ") ON DUPLICATE KEY UPDATE
      名称=“ABC”,城市=“XYZ”

      有关更多帮助,请参阅文档。 Click here

      【讨论】:

        【解决方案5】:

        您可以使用EXISTS 关键字来检查行的存在:

        IF EXISTS (SELECT TOP 1 * FROM...)
        BEGIN
            UPDATE....
        END
        ELSE
        BEGIN
           INSERT...
        END
        

        【讨论】:

        • 只运行更新并检查更新了多少行会更有效。
        【解决方案6】:

        只需识别数据集中的唯一项(如Id或代码)。然后通过使用它尝试首先执行 SELECT 查询。如果 Resultset 为空,请执行 INSERT 否则尝试 UPDATE 详细信息。

        【讨论】:

          【解决方案7】:

          您必须首先检查表中是否存在数据 如果存在则使用更新查询,否则插入数据 很简单

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-08-21
            • 1970-01-01
            • 1970-01-01
            • 2014-10-23
            相关资源
            最近更新 更多