14

I want to create a script to fill a database for testing. How would I set a string to be hashed and the inserted into the database?

I have:

INSERT INTO `loop`.`User`
(`userID`,
`firstName`,
`lastName`,
`email`,
`password`,
`userName`,
`bio`,
`spamCount`)
VALUES
('gZvTtlPtjGRqeMBaLji3HxoKB5EZCsNL',
'Joe',
'Smith',
'[email protected]',
SHA2('testgZvTtlPtjGRqeMBaLji3HxoKB5EZCsNL', 256),
'[email protected]',
"TEST BIO",
0);

How do I hash the string and INSERT in same statement?

1
  • 1
    what error are you getting?
    – davejal
    Commented Jan 11, 2016 at 1:01

2 Answers 2

37

You can insert a SELECT instead of VALUES to run a function on one of the inputs:

INSERT INTO `loop`.`User`
(`userID`,
 `firstName`,
 `lastName`,
 `email`,
 `password`,
 `userName`,
 `bio`,
 `spamCount`)
SELECT
'gZvTtlPtjGRqeMBaLji3HxoKB5EZCsNL',
'Joe',
'Smith',
'[email protected]',
SHA2('testgZvTtlPtjGRqeMBaLji3HxoKB5EZCsNL', 256),
'[email protected]',
"TEST BIO",
0;
3
  • Could you explain this a little more? I want to understand.
    – John Down
    Commented Jan 11, 2016 at 1:06
  • 7
    When you insert VALUES they have to be straight up values (strings, integers, etc.) rather than functions or subqueries that resolve to values. When using a SELECT statement, however, one is not constrained in this way.
    – wogsland
    Commented Jan 11, 2016 at 1:07
  • Thank you that makes sense!
    – John Down
    Commented Jan 11, 2016 at 1:10
2

If you already have the table filled by some content, you can alter it with the following :

ALTER TABLE `page` ADD COLUMN `hash` char(64) AS (SHA2(`content`, 256)) AFTER `content`

This solution will add hash column right after the content one, generates hash for existing and new records too without need to change your INSERT statement.

Not the answer you're looking for? Browse other questions tagged or ask your own question.