14

This is a question based on absolute no knowledge of golang and the aim is to find if there is a way to make long queries readable.

My attempt is to put the sql text in a variable and then execute the variable.

Pseudocode (no real code):

var query = SELECT * FROM foo UNION ALL SELECT * FROM bar UNION ALL SELECT * FROM other ... db.prepare (var query) db.query (var query) 

This is maybe a dumb question, but I have searched and found no clue how to make long queries more "readable" in go. Most examples are based on "hello world" level. In the real world queries can be quite long.

TIA,

5
  • You could use a multiline string? Commented Mar 27, 2016 at 7:12
  • You mean to declare a variable as multiline string? Commented Mar 27, 2016 at 7:17
  • 1
    yeah, declare the query as a multiline string literal. Commented Mar 27, 2016 at 7:21
  • Thank you! First step to understand. Any example? Commented Mar 27, 2016 at 7:38
  • I posted an answer with a simple example. Commented Mar 27, 2016 at 7:45

2 Answers 2

31

You can declare the query as a multiline string literal.

query := ` SELECT * FROM foo UNION ALL SELECT * FROM bar UNION ALL SELECT * FROM other` 

And use it with DB.Query.

rows, err := db.Query(query) 

There are many different drivers for many different sql databases you can use. They all would give you a DB object to work with. So you can use DB.Prepare, DB.Query appropriately. Check docs of database/sql package for more info.

Sign up to request clarification or add additional context in comments.

Comments

1

There are two methods for this

1. Using backquote: Use (backquote\backtick) which is with symbol ` in keyboard. So that your query will look like

query := `INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country) VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');` 

2. Using string concatenation: Use string concatenation characters between lines So that your query will look like

query :="INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)"+ "VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');" 

I prefer the 1st one :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.