Explain Codes LogoExplain Codes Logo

Execute SQL script from command line

sql
sqlcmd
automation
backup
Anton ShumikhinbyAnton Shumikhin·Aug 4, 2024
TLDR

To execute a SQL script from the command line, match the tool to your SQL database. Here's your quick guide:

  • MySQL/MariaDB:

    mysql -u user -p db_name < file.sql
  • PostgreSQL:

    psql -U user -d db_name -f file.sql
  • SQL Server:

    sqlcmd -S server -d db_name -U user -P password -i file.sql
  • SQLite:

    sqlite3 db_name < file.sql

Replace user, db_name, file.sql, server, and password with your specific credentials and the path to your SQL file. Then, blow the command line trumpet and let your database dance.

Fine-Tuning SQL commands

Embrace Integrated Security with sqlcmd

Rather than risking credentials exposure through the command line, use -E flag to harness Integrated Security with sqlcmd.

sqlcmd -S server -d db_name -E -i file.sql

Master single command execution

Solve small problems swiftly with -Q flag—an express ticket to run a single SQL statement and finish the sqlcmd session.

sqlcmd -S server -d db_name -E -Q "SELECT * FROM my_table"
<!-- This is where you SELECT your destiny from a table called life. 😄 -->

Redirect output to a file

Channel the output to a file using -o flag for later data digestion or record keeping.

sqlcmd -S server -d db_name -E -i file.sql -o output.txt
<!-- Because nobody has time to monitor real-time data magic. 🎩 -->

Secure and Automate your Script Execution

Safeguard sensitive information

To prevent your password from taking a public walk, prefer Integrated Security or lean on configuration files and environment variables.

Automate with batch files and sqlcmd

sqlcmd + batch scripting = your arsenal for automating and streamlining database operations. Make sure to test in multiple scenarios for seamless implementation.

<!-- Bash the bash with sqlcmd! 🥁 -->

Safeguarding your Data and Troubleshooting Scripts

Test in a non-production environment

A non-production environment is a safe playground. Test there first to avoid waking up any sleeping bugs in the real world.

Maintain regular database backups

Before you put your destructive commands on the run, be sure to pack your parachute—make up-to-date backups of your database.

Wise use of community resources for error handling

Don't dwell on errors; leverage developer communities or consult the SQL Server Express community to turn your problems into solutions.

<!-- You're part of an SQL-wesome community! 💪 -->