Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a sql file

I have .sql file which has lots of database creation, deletion, population stuff. Is it possible to have a go function which can excute a sql file. I am using postgres as my database and using lib/pq driver for all database transactions. But I am open to any library for executing this sql file in my Go project.

like image 657
codec Avatar asked Aug 17 '16 13:08

codec


People also ask

How do I run a SQL database File?

Click Query > Connection > Connect to connect to the server that contains the database you want to access. Select the appropriate StarTeam Server database. Open the tuning script, by choosing File > Open > foldername\scriptname. Execute the script, by clicking the Execute button on the toolbar or by pressing F5.


1 Answers

It's too much trouble if you are going to execute it using a command line. You have to deal with issues like setting your passwords, making sure the path variables are properly set, etc. I think the bets way is to use the database driver and just call it using Go.

In the following example, I'm using pgx implementation of sql driver for Postgres. You can do it with any driver implementation of your choice.

path := filepath.Join("path", "to", "script.sql")

c, ioErr := ioutil.ReadFile(path)
if ioErr != nil {
   // handle error.
}
sql := string(c)
_, err := *pgx.Conn.Exec(sql)
if err != nil {
  // handle error.
}

Explanation:

  1. Get the path to your sql script in a os agnostic way.
  2. Read the content of the file to string.
  3. Execute the statements in the file using the sql driver.
like image 103
kovac Avatar answered Oct 13 '22 02:10

kovac