Batch script to issue commands to mySQL db?

2019-05-21 10:35发布

I am trying to create a batch script that would connect to a mySQL database and issue a delete command:

@echo off
echo Resetting all assessments...
mysql -hlocalhost -urdfdev -p%1 rdf_feedback
delete from competency_question_answer;

I will run this script providing the password as a command-line argument, but all this script does is, connects to the database, and the mysql> prompt will be shown. After I exit from mysql, the rest of the batch commands get to execute (and fail, no surprise).

How can I pass the SQL commands from the batch script to the mysql console? Is this even possible?

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-05-21 10:51

You may need to connect multiple times:

@echo off
echo Resetting all assessments...
mysql -hlocalhost -urdfdev -p%1 rdf_feedback -e delete from competency_question_answer;

Alternatively, you should be able to put all your commands in a separate file such as input.sql and use:

mysql -hlocalhost -urdfdev -p%1 rdf_feedback <input.sql
查看更多
一纸荒年 Trace。
3楼-- · 2019-05-21 10:59

Putting multiple sets of commands into .sql batch files works best, and you can execute multiples of these in the .bat file.

查看更多
爷、活的狠高调
4楼-- · 2019-05-21 11:06

echo "delete from competency_question_answer;" | mysql -hlocalhost -ur... etc.

查看更多
再贱就再见
5楼-- · 2019-05-21 11:10

You need to use command line tools. I don't know if there exists any for MySQL but for SQL there is SQLCMD and for Oracle there is OSQL.

What you can also do is something like this.

mysql -uuser -ppass < foo.sql

Where foo.sql is the commands you want to execute.

查看更多
登录 后发表回答