Get table ID after insert with ColdFusion and MySQL

前端 未结 5 432
遥遥无期
遥遥无期 2021-01-04 02:33

My normal process for inserting into one table and then getting the ID back so that I can insert into another table is like this in MSSQL:

DECLARE @transacti         


        
5条回答
  •  南方客
    南方客 (楼主)
    2021-01-04 03:12

    Part 1: I would personally not batch multiple statements within a single query to reduce the risk of SQL injection. This is a setting within your datasource on the ColdFusion administrator. Executing a stored procedure, which might be what you are doing(?), is another story, but, you should rephrase your question to "Get primary key after insert with mySQL Stored Procedure" if that is your intention.

    Part 2: ColdFusion, like many things, makes getting the primary key for a newly inserted record very easy--even if you are using auto-increment keys, GUIDs or something like Oracle's ROWNUM. This will work on any almost every database supported by Adobe ColdFusion including MSSQL or MySQL. The only exception is the version of the databse--for example, MySQL 3 will not support this; however, MySQL 4+ will.

    
      INSERT INTO myTable (
          title
      ) VALUES (
        
      )
    
    
    <--- get the primary key of the inserted record --->
    
    

    As of CF9+, you can access the new ID (for any database) using the generic key name:

    result.GENERATEDKEY    // All databases
    

    For CF8, different databases will have different keys within the results value. Here is a simple table to help I copied from the cfquery documentation.

    result.identitycol    // MSSQL
    result.rowid          // Oracle
    result.sys_identity   // Sybase
    result.serial_col     // Informix
    result.generated_key  // MySQL
    

    If you have any questions you can see a pretty dump as follows:

    
    

提交回复
热议问题