如何生成随机字符并使用 MySQL 插入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8207380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate random chars and insert with MySQL?
提问by spotlightsnap
How can I generate 100 records with 5 random characters and insert into the database with a query.
如何使用 5 个随机字符生成 100 条记录并通过查询插入到数据库中。
I want to insert into this table:
我想插入到这个表中:
codes
id (auto-increment)
codes
回答by Devart
Try this one -
试试这个——
SELECT CONCAT(
CHAR( FLOOR(65 + (RAND() * 25))),
CHAR( FLOOR(65 + (RAND() * 25))),
CHAR( FLOOR(65 + (RAND() * 25))),
CHAR( FLOOR(65 + (RAND() * 25))),
CHAR( FLOOR(65 + (RAND() * 25)))
) random_string;
This query generates ASCII codes from 'A' to 'Z' and generates a random string from them. I cannot say that this way is elegant, but it works;-)
此查询生成从“A”到“Z”的 ASCII 代码,并从中生成随机字符串。我不能说这种方式很优雅,但它确实有效;-)
回答by ScottJShea
INSERT INTO codes_tbl (codes) VALUES (SUBSTRING(MD5(RAND()) FROM 1 FOR 5));
That should take care of it.
那应该照顾它。
回答by ScoRpion
In MySql U Can Do It Like This
在 MySql 中你可以这样做
insert into table ( SUBSTRING(MD5(RAND()) FROM 1 FOR 10) , field2 , field3) , ( SUBSTRING(MD5(RAND()) FROM 1 FOR 10) , field2 , field3) , .........
If You Want to Do it With Php. U CanCheck This Link
如果你想用 PHP 来做。你可以检查这个链接
Further You can Check The Following Questions Already asked at Stackoverflow
此外,您可以检查 Stackoverflow 上已经提出的以下问题
回答by Nonym
Could you try this out?:
你能试试这个吗?:
CREATE DEFINER=`root`@`localhost` PROCEDURE `InsertOneHundredRandomCodes` ()
BEGIN
DECLARE ctr INT DEFAULT 0;
hundred_loop:LOOP
SET ctr = ctr + 1; -- increment
-- insert command here
INSERT INTO codes (codes)
SELECT SUBSTRING(MD5(RAND()) FROM 1 FOR 5) AS codes;
IF ctr = 100 THEN -- check if we should stop
LEAVE hundred_loop;
END IF;
END LOOP hundred_loop;
END//
Create that procedure then run this command:
创建该过程然后运行以下命令:
CALL InsertOneHundredRandomCodes();
It should insert into codes
100 random values for the codes
value.
它应该codes
为该codes
值插入100 个随机值。