插入数据,如果已插入,则在sql中更新

时间:2016-04-06 05:30:53

标签: java sql

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

7 个答案:

答案 0 :(得分:5)

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

由于您没有指定您所询问的DBMS方言,我将向您推荐维基百科文章“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

答案 1 :(得分:4)

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

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

答案 2 :(得分:2)

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

答案 3 :(得分:2)

只需在数据集中标识唯一商品(例如 ID 代码)。然后使用该尝试首先执行 SELECT 查询。如果结果集为空,请执行 INSERT ,然后尝试更新详细信息。

答案 4 :(得分:2)

尝试按照以下方式:

示例查询

INSERT INTO表(id,name,city)VALUES(1," ABC"," XYZ")ON DUPLICATE KEY UPDATE
name =" ABC",city =" XYZ"

获取更多帮助,请参阅文档。 Click here

答案 5 :(得分:1)

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

使用 SELECT 查询 从EmployeeDetails中选择*,其中employee_id ="唯一键值&#34 ;; 如果结果集不为空,则使用 UPDATE 查询来更新字段。

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

插入EmployeeDetails值(...)

答案 6 :(得分:1)

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();
  }
}
}