How can I get the results of a SQL query in the shell?
In the shell, you can use command line tools to execute SQL and retrieve results. The specific command line tool depends on the database system you are using. Here are some common database systems and their corresponding command line tools:
- MySQL: MySQL command line tool
- PostgreSQL: psql command line tool
- The sqlplus command line tool is from Oracle.
- SQLite: sqlite3 command line tool
When using these command line tools, you can input SQL files or SQL statements using redirection operators, and output the results to either the standard output or a file. For example, if you have saved your SQL statement in a file called query.sql, you can use the following command to execute the SQL and output the results to the standard output:
mysql -u username -p password -h hostname -D database < query.sql
The -u parameter specifies the database username, the -p parameter specifies the database password, the -h parameter specifies the database hostname, and the -D parameter specifies the database name. You can modify these parameters according to the actual situation. Finally, < query.sql indicates reading SQL statements from the query.sql file.
You can use the redirection operator “>” if you want to save the results to a file. For example:
mysql -u username -p password -h hostname -D database < query.sql > result.txt
This will execute the SQL and save the results to the file result.txt.