0

I have a table named my_table that contains rows for hash_value, file_name, file_contents, and id.

I have a program that accepts a hash value from the user.

I would like to take this value and create a mysql batch that will dump the file out to file_name

I can create a batch to dump the file contents using

SELECT file_contents INTO DUMPFILE 'myfilename' FROM my_table WHERE hash_value='myhashvalue';

but I have not been able to find a way to get file_name first and use that in the command. I would also like a way to let my program know if the batch failed and why (no such hash in table, file exists already, etc)

pseudo code

@file_name = SELECT file_name FROM my_table WHERE hash_value='myhashvalue';
if @file_name is not empty
    SELECT file_contents INTO DUMPFILE @file_name FROM my_table WHERE hash_value='myhashvalue';
    // if file exists already then the error gets sent to stdout so I can determine that
else
    echo something to stdout so I know the user entered a value not in the table
endif

I am running this batch in the followng manner

mysql -h localhost -u theuser -pthepassword mydatabase < mybatch.sql

Thank you

EDIT: I am getting closer. I am able to set the file name using

SELECT @filename:=file_name FROM my_table WHERE hash_value='myhahsvalue';

but I get an error when trying to use this in my next statement SELECT file_contents INTO DUMPFILE @filename FROM my_table WHERE hash_value='myhashvalue';

results in You have an error in your SQL syntax;

EDIT 2: I can now get the file name (if it exists based on the hash) using this. I am still working on the error reporting part, but this works well

SELECT @filename:=file_name FROM my_table WHERE hash_value='myhashvalue';
SET @query:=CONCAT("SELECT file_contents INTO DUMPFILE '",@filename,"' FROM mytable WHERE hash_value='myhashvalue'");
PREPARE stmt FROM @query;
EXECUTE stmt;
4

2 回答 2

0

我有一个程序可以接受用户的哈希值。

大概有一个原因,您为什么不简单地修改这个程序来调用 SQL?如果它所做的只是读取一个值,那么它是什么实用程序?

使用 mysql 过程读取文件名,将其分配给变量并调整查询:

CREATE PROCEDURE extract (IN hash_in VARCHAR(100))
DETERMINISTIC
BEGIN
   DECLARE fname VARCHAR(100);
   SELECT file_name INTO fname FROM my_table WHERE hash_value=hash_in LIMIT 0,1;
   SELECT file_contents 
     INTO DUMPFILE fname 
     FROM my_table WHERE hash_value=hash_in;
END;
于 2013-09-13T12:40:06.940 回答
0

我不是“最佳”解决方案,而是添加了 --verbose ,然后在末尾添加了 2>&1 以将 stderr 重定向到 stdout。然后可以解析错误代码的文本。ERROR 1064 如果输入了无效的哈希,mysql 执行失败 如果文件已经存在,则 ERROR 1086 感谢查看

于 2013-09-13T11:57:14.883 回答