Query Select and Insert if not exists

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
0
down vote

favorite












Are there any good ways to make this createIndexBlock() method shorter?



It looks wastefully long. I have many tables. I don't like to make these kinds of methods.



import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)

var db, _ = sql.Open("mysql", "xxx:xxx@(database:3306)/xx")

func createIndexBlock(blockHash string) int64

rows, err := db.Query("SELECT id FROM index_blocks WHERE `hash`=? LIMIT 1", blockHash)
if err != nil
panic(err.Error())


for rows.Next()
var id int64
err := rows.Scan(&id)
if err != nil
panic(err.Error())

rows.Close()
return id


result, err := db.Exec("INSERT INTO index_blocks (`hash`) values (?)", blockHash)
if err != nil
panic(err.Error())


id, err := result.LastInsertId()
if err != nil
panic(err.Error())


return id







share|improve this question





















  • As per the How to Ask guidelines, please tell us more about what this code accomplishes, and why you are doing it. What does the definition of the index_blocks table look like, and what is it for?
    – 200_success
    Feb 6 at 13:29
















up vote
0
down vote

favorite












Are there any good ways to make this createIndexBlock() method shorter?



It looks wastefully long. I have many tables. I don't like to make these kinds of methods.



import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)

var db, _ = sql.Open("mysql", "xxx:xxx@(database:3306)/xx")

func createIndexBlock(blockHash string) int64

rows, err := db.Query("SELECT id FROM index_blocks WHERE `hash`=? LIMIT 1", blockHash)
if err != nil
panic(err.Error())


for rows.Next()
var id int64
err := rows.Scan(&id)
if err != nil
panic(err.Error())

rows.Close()
return id


result, err := db.Exec("INSERT INTO index_blocks (`hash`) values (?)", blockHash)
if err != nil
panic(err.Error())


id, err := result.LastInsertId()
if err != nil
panic(err.Error())


return id







share|improve this question





















  • As per the How to Ask guidelines, please tell us more about what this code accomplishes, and why you are doing it. What does the definition of the index_blocks table look like, and what is it for?
    – 200_success
    Feb 6 at 13:29












up vote
0
down vote

favorite









up vote
0
down vote

favorite











Are there any good ways to make this createIndexBlock() method shorter?



It looks wastefully long. I have many tables. I don't like to make these kinds of methods.



import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)

var db, _ = sql.Open("mysql", "xxx:xxx@(database:3306)/xx")

func createIndexBlock(blockHash string) int64

rows, err := db.Query("SELECT id FROM index_blocks WHERE `hash`=? LIMIT 1", blockHash)
if err != nil
panic(err.Error())


for rows.Next()
var id int64
err := rows.Scan(&id)
if err != nil
panic(err.Error())

rows.Close()
return id


result, err := db.Exec("INSERT INTO index_blocks (`hash`) values (?)", blockHash)
if err != nil
panic(err.Error())


id, err := result.LastInsertId()
if err != nil
panic(err.Error())


return id







share|improve this question













Are there any good ways to make this createIndexBlock() method shorter?



It looks wastefully long. I have many tables. I don't like to make these kinds of methods.



import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)

var db, _ = sql.Open("mysql", "xxx:xxx@(database:3306)/xx")

func createIndexBlock(blockHash string) int64

rows, err := db.Query("SELECT id FROM index_blocks WHERE `hash`=? LIMIT 1", blockHash)
if err != nil
panic(err.Error())


for rows.Next()
var id int64
err := rows.Scan(&id)
if err != nil
panic(err.Error())

rows.Close()
return id


result, err := db.Exec("INSERT INTO index_blocks (`hash`) values (?)", blockHash)
if err != nil
panic(err.Error())


id, err := result.LastInsertId()
if err != nil
panic(err.Error())


return id









share|improve this question












share|improve this question




share|improve this question








edited Mar 9 at 4:51









200_success

123k14143401




123k14143401









asked Feb 6 at 11:46









zono

12414




12414











  • As per the How to Ask guidelines, please tell us more about what this code accomplishes, and why you are doing it. What does the definition of the index_blocks table look like, and what is it for?
    – 200_success
    Feb 6 at 13:29
















  • As per the How to Ask guidelines, please tell us more about what this code accomplishes, and why you are doing it. What does the definition of the index_blocks table look like, and what is it for?
    – 200_success
    Feb 6 at 13:29















As per the How to Ask guidelines, please tell us more about what this code accomplishes, and why you are doing it. What does the definition of the index_blocks table look like, and what is it for?
– 200_success
Feb 6 at 13:29




As per the How to Ask guidelines, please tell us more about what this code accomplishes, and why you are doing it. What does the definition of the index_blocks table look like, and what is it for?
– 200_success
Feb 6 at 13:29










1 Answer
1






active

oldest

votes

















up vote
3
down vote













It seems to me that you are trying to retrieve the ID of a specific blockHash in the database, and if the entry does not exist, you want to create a new entry. This is where INSERT ... ON DUPLICATE KEY UPDATE comes in handy.



INSERT INTO `index_blocks` (`hash`) VALUES (?) 
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
SELECT LAST_INSERT_ID();


Here's what you can do:



func createIndexBlock(blockHash string) int64 
result, err := db.Exec(`INSERT INTO index_blocks (hash) VALUES (?)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)`, blockHash)
if err != nil
panic(err.Error())


id, err := result.LastInsertId()
if err != nil
panic(err.Error())

return id



Alternatively, you can look into INSERT IGNORE, followed by a SELECT. That will work too.






share|improve this answer





















    Your Answer




    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );








     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f186909%2fquery-select-and-insert-if-not-exists%23new-answer', 'question_page');

    );

    Post as a guest






























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    3
    down vote













    It seems to me that you are trying to retrieve the ID of a specific blockHash in the database, and if the entry does not exist, you want to create a new entry. This is where INSERT ... ON DUPLICATE KEY UPDATE comes in handy.



    INSERT INTO `index_blocks` (`hash`) VALUES (?) 
    ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
    SELECT LAST_INSERT_ID();


    Here's what you can do:



    func createIndexBlock(blockHash string) int64 
    result, err := db.Exec(`INSERT INTO index_blocks (hash) VALUES (?)
    ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)`, blockHash)
    if err != nil
    panic(err.Error())


    id, err := result.LastInsertId()
    if err != nil
    panic(err.Error())

    return id



    Alternatively, you can look into INSERT IGNORE, followed by a SELECT. That will work too.






    share|improve this answer

























      up vote
      3
      down vote













      It seems to me that you are trying to retrieve the ID of a specific blockHash in the database, and if the entry does not exist, you want to create a new entry. This is where INSERT ... ON DUPLICATE KEY UPDATE comes in handy.



      INSERT INTO `index_blocks` (`hash`) VALUES (?) 
      ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
      SELECT LAST_INSERT_ID();


      Here's what you can do:



      func createIndexBlock(blockHash string) int64 
      result, err := db.Exec(`INSERT INTO index_blocks (hash) VALUES (?)
      ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)`, blockHash)
      if err != nil
      panic(err.Error())


      id, err := result.LastInsertId()
      if err != nil
      panic(err.Error())

      return id



      Alternatively, you can look into INSERT IGNORE, followed by a SELECT. That will work too.






      share|improve this answer























        up vote
        3
        down vote










        up vote
        3
        down vote









        It seems to me that you are trying to retrieve the ID of a specific blockHash in the database, and if the entry does not exist, you want to create a new entry. This is where INSERT ... ON DUPLICATE KEY UPDATE comes in handy.



        INSERT INTO `index_blocks` (`hash`) VALUES (?) 
        ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
        SELECT LAST_INSERT_ID();


        Here's what you can do:



        func createIndexBlock(blockHash string) int64 
        result, err := db.Exec(`INSERT INTO index_blocks (hash) VALUES (?)
        ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)`, blockHash)
        if err != nil
        panic(err.Error())


        id, err := result.LastInsertId()
        if err != nil
        panic(err.Error())

        return id



        Alternatively, you can look into INSERT IGNORE, followed by a SELECT. That will work too.






        share|improve this answer













        It seems to me that you are trying to retrieve the ID of a specific blockHash in the database, and if the entry does not exist, you want to create a new entry. This is where INSERT ... ON DUPLICATE KEY UPDATE comes in handy.



        INSERT INTO `index_blocks` (`hash`) VALUES (?) 
        ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
        SELECT LAST_INSERT_ID();


        Here's what you can do:



        func createIndexBlock(blockHash string) int64 
        result, err := db.Exec(`INSERT INTO index_blocks (hash) VALUES (?)
        ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)`, blockHash)
        if err != nil
        panic(err.Error())


        id, err := result.LastInsertId()
        if err != nil
        panic(err.Error())

        return id



        Alternatively, you can look into INSERT IGNORE, followed by a SELECT. That will work too.







        share|improve this answer













        share|improve this answer



        share|improve this answer











        answered Mar 9 at 1:30









        Jay Lim

        1413




        1413






















             

            draft saved


            draft discarded


























             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f186909%2fquery-select-and-insert-if-not-exists%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            Greedy Best First Search implementation in Rust

            Function to Return a JSON Like Objects Using VBA Collections and Arrays

            C++11 CLH Lock Implementation