开发者

Groovy Script to insert database entries with unique key

开发者 https://www.devze.com 2023-04-07 19:36 出处:网络
I am writing a groovy script to read data from an CSV file and then pull inserts into database. I have gotten everything to work EXCEPT for g开发者_运维百科enerating a unique primary key or autoincrem

I am writing a groovy script to read data from an CSV file and then pull inserts into database. I have gotten everything to work EXCEPT for g开发者_运维百科enerating a unique primary key or autoincrement for each insert. The unique key is campusID. Here is the script.

def sql = Sql.newInstance("jdbc:mysql://localhost:3306/mydb",
        "xxxx", "xxxx", "com.mysql.jdbc.Driver")
      def campus = sql.dataSet("CAMPUS")



new File("C:\\test.csv").splitEachLine(",") {fields ->
        campus.add(
          campusId: // Need to generate a unique key here

          campusShortName: fields[1],
          campusUrl: fields[2])

Thanks.


The unique key is usually handled by the database, not by the code.

Some databases (like MySQL) accept setting the autogenerated field to null, others require that the column isn't provided at all. So, either remove the campusId from your query, or set it to null, and make sure the column is set to be an AUTO_INCREMENT column.

If you need the ID that was inserted (for example, to use as a foreign key), you may be better off using the normal SQL methods, and check the return value of the executeInsert method

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号