# New to Go: SQL to CSV

**URL:** <https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955>\
**Category:** Getting Help\
**Created:** [December 27, 2018, 8:34am UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955 "2018-12-27T08:34:37Z")\
**Posts on this page:** 14\
**Page:** 2

<div class="post-metadata">

**Author:** ![John\_Denny](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/john_denny/32/7672_2.png) [@John\_Denny](https://forum.golangbridge.org/u/John_Denny)\
**Post date:** [December 28, 2018, 12:30pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/24 "2018-12-28T12:30:33Z")

</div>

appreciate it.

---

<div class="post-metadata">

**Author:** ![Locust](https://forum.golangbridge.org/letter_avatar_proxy/v4/letter/l/898d66/32.png) [@Locust](https://forum.golangbridge.org/u/Locust)\
**Post date:** [December 28, 2018, 12:48pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/25 "2018-12-28T12:48:38Z")

</div>

I added the log.Println line so I can see the output, and it goes though the 3 db’s but only dumps lines of data from the last db it sees to the csv. so progress thanks.

Try to replace

```auto
file, err := os.Create("result.csv")

```

with

```auto
file, err := os.Create(database_name)

```

---

<div class="post-metadata">

**Author:** ![Locust](https://forum.golangbridge.org/letter_avatar_proxy/v4/letter/l/898d66/32.png) [@Locust](https://forum.golangbridge.org/u/Locust)\
**Post date:** [December 28, 2018, 1:05pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/26 "2018-12-28T13:05:50Z")

</div>

“each line had lots of string= comments”

You can get rid of the types before the values (string=… ) by changing the Sprinf  
from

```auto
a:=fmt.Sprintf(server_name,database_name,recovery_model_desc,last_full_backup,last_diff_backup,last_tran_backup,days_since_full_backup,days_since_diff_backup,hours_since_tranlog_backup,full_backup_location,diff_backup_location,tlog_backup_location)

```

to

```auto
a:= fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s" , server_name,database_name,recovery_model_desc,last_full_backup,last_diff_backup,last_tran_backup,days_since_full_backup,days_since_diff_backup,hours_since_tranlog_backup,full_backup_location,diff_backup_location,tlog_backup_location)

```

---

<div class="post-metadata">

**Author:** ![John\_Denny](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/john_denny/32/7672_2.png) [@John\_Denny](https://forum.golangbridge.org/u/John_Denny)\
**Post date:** [December 28, 2018, 3:33pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/27 "2018-12-28T15:33:11Z")

</div>

Interesting - Create some random text files named after each of the 6 databases seen by the query with differing information in them.

I guess I need to work out how to open the csv leave open , file with the results from all the db scans then close. If that’s possible.

---

<div class="post-metadata">

**Author:** ![Locust](https://forum.golangbridge.org/letter_avatar_proxy/v4/letter/l/898d66/32.png) [@Locust](https://forum.golangbridge.org/u/Locust)\
**Post date:** [December 28, 2018, 3:39pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/28 "2018-12-28T15:39:44Z")

</div>

You could make the slice “a” a global variable and then write the file after the loop where you read the db data is finished, at the end of the main function.

---

<div class="post-metadata">

**Author:** ![John\_Denny](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/john_denny/32/7672_2.png) [@John\_Denny](https://forum.golangbridge.org/u/John_Denny)\
**Post date:** [December 28, 2018, 3:45pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/29 "2018-12-28T15:45:10Z")

</div>

If I was a coder yes, but alas I’m a just messing. I think I follow the logic. And again thanks Ill play.

---

<div class="post-metadata">

**Author:** ![Locust](https://forum.golangbridge.org/letter_avatar_proxy/v4/letter/l/898d66/32.png) [@Locust](https://forum.golangbridge.org/u/Locust)\
**Post date:** [December 28, 2018, 3:52pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/30 "2018-12-28T15:52:33Z")

</div>

> [@John\_Denny](#):
>
> var mapofrows string

That´s straight forward, you move

```auto
var mapofrows []string

```

to the top, same place where you have the var db

and then move

```auto
file, err := os.Create("result.csv")
checkError("Cannot create file", err)
defer file.Close()
writer := csv.NewWriter(file)
defer writer.Flush()
err = writer.Write(mapofrows)
checkError("Cannot write to file", err)

```

to the end of your code in the main function.  
Now the data from all 3 db´s is accumulated in the slice and then saved.

---

<div class="post-metadata">

**Author:** ![John\_Denny](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/john_denny/32/7672_2.png) [@John\_Denny](https://forum.golangbridge.org/u/John_Denny)\
**Post date:** [December 28, 2018, 3:55pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/31 "2018-12-28T15:55:55Z")

</div>

I see, so its known to whole project. I had some success with the sqltocsv module, which I might also try and use use you split with to give me another idea. cheers.

I’ve done that, and it now has got all the data from all the rows.

Only small issue is the excel formatting, each line of data is actual inserted into a cell, so I have 14 cells rather that 14 lines. lol

Assuming I put the code in right area.

```auto
// Get values from row.
        err := rows.Scan(&server_name,&database_name,&recovery_model_desc,&last_full_backup,&last_diff_backup,&last_tran_backup,&days_since_full_backup,&days_since_diff_backup,&hours_since_tranlog_backup,&full_backup_location,&diff_backup_location,&tlog_backup_location)
        if err != nil {
            return -1, err
        }
        
		
		a:= fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s" , server_name,database_name,recovery_model_desc,last_full_backup,last_diff_backup,last_tran_backup,days_since_full_backup,days_since_diff_backup,hours_since_tranlog_backup,full_backup_location,diff_backup_location,tlog_backup_location)
        mapofrows=append(mapofrows,a)
		
    count++   
	
    
}
	file, err := os.Create("result.csv")
	checkError("Cannot create file", err)
	defer file.Close()
	writer := csv.NewWriter(file)
	defer writer.Flush()
	err = writer.Write(mapofrows)
	checkError("Cannot write to file", err)		

    return count, nil
	

}

func checkError(message string, err error) {
    if err != nil {
        log.Fatal(message, err)
    }
	
}
```

---

<div class="post-metadata">

**Author:** ![John\_Denny](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/john_denny/32/7672_2.png) [@John\_Denny](https://forum.golangbridge.org/u/John_Denny)\
**Post date:** [January 2, 2019, 3:03pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/32 "2019-01-02T15:03:01Z")

</div>

Is there anyway to control how the csv is built up, as in to populate each row of sql data to a separate row in the csv? rather than it dumping it all into cells on one row.  
cheers in advance.

---

<div class="post-metadata">

**Author:** ![Yamil\_Bracho](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/yamil_bracho/32/5141_2.png) [@Yamil\_Bracho](https://forum.golangbridge.org/u/Yamil_Bracho)\
**Post date:** [January 2, 2019, 5:54pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/33 "2019-01-02T17:54:21Z")

</div>

yes, just do this :

file, err := os.Create(“result.csv”)  
checkError(“Cannot create file”, err)  
defer file.Close()  
writer := csv.NewWriter(file)  
defer writer.Flush()

…

// Get values from row.  
err := rows.Scan(&server\_name,&database\_name,&recovery\_model\_desc,&last\_full\_backup,&last\_diff\_backup,&last\_tran\_backup,&days\_since\_full\_backup,&days\_since\_diff\_backup,&hours\_since\_tranlog\_backup,&full\_backup\_location,&diff\_backup\_location,&tlog\_backup\_location)  
if err != nil {  
return -1, err  
}  
row := make([]string, 0)  
row = append(row, server\_name)  
row = append(row, database\_name)  
row = append(row, recovery\_model\_desc)  
row = append(row, last\_full\_backup)  
row = append(row, last\_diff\_backup)  
row = append(row, last\_tran\_backup)  
row = append(row, days\_since\_full\_backup)  
row = append(row, days\_since\_diff\_backup)  
row = append(row, hours\_since\_tranlog\_backup)  
row = append(row, full\_backup\_location)  
row = append(row, diff\_backup\_location)  
row = append(row, tlog\_backup\_location)

err = writer.Write(row)  
checkError(“Cannot write to file”, err)

count++

}

return count, nil

---

<div class="post-metadata">

**Author:** ![John\_Denny](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/john_denny/32/7672_2.png) [@John\_Denny](https://forum.golangbridge.org/u/John_Denny)\
**Post date:** [January 2, 2019, 6:25pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/34 "2019-01-02T18:25:52Z")

</div>

Thanks for the advice. If I understand changes after the select as below.

```auto
	tsql := fmt.Sprintf(sql)

	file, err := os.Create("result.csv")
    checkError("Cannot create file", err)
    defer file.Close()
    writer := csv.NewWriter(file)
    defer writer.Flush()
   
	 var count int
	 var server_name string
	 var database_name string
	 var recovery_model_desc string
	 var last_full_backup string
	 var last_diff_backup string
	 var last_tran_backup string
	 var days_since_full_backup string
	 var days_since_diff_backup string
	 var hours_since_tranlog_backup string
	 var full_backup_location string
	 var diff_backup_location string
     var tlog_backup_location string

    rows, err := db.QueryContext(ctx, tsql)
    if err != nil {
        return -1, err
    }
    defer rows.Close()
	

    for rows.Next() {
// Get values from row.
err := rows.Scan(&server_name,&database_name,&recovery_model_desc,&last_full_backup,&last_diff_backup,&last_tran_backup,&days_since_full_backup,&days_since_diff_backup,&hours_since_tranlog_backup,&full_backup_location,&diff_backup_location,&tlog_backup_location)
if err != nil {
return -1, err
}
row := make([]string, 0)
row = append(row, server_name)
row = append(row, database_name)
row = append(row, recovery_model_desc)
row = append(row, last_full_backup)
row = append(row, last_diff_backup)
row = append(row, last_tran_backup)
row = append(row, days_since_full_backup)
row = append(row, days_since_diff_backup)
row = append(row, hours_since_tranlog_backup)
row = append(row, full_backup_location)
row = append(row, diff_backup_location)
row = append(row, tlog_backup_location)

fmt.Println(row)

err = writer.Write(row)
checkError("Cannot write to file", err)  
count ++
}
  
err = rows.Err()
if err != nil {
    panic(err)
}

    return count, nil

}

func checkError(message string, err error) {
    if err != nil {
        log.Fatal(message, err)
    }
	
}
```

---

<div class="post-metadata">

**Author:** ![John\_Denny](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/john_denny/32/7672_2.png) [@John\_Denny](https://forum.golangbridge.org/u/John_Denny)\
**Post date:** [January 2, 2019, 9:02pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/35 "2019-01-02T21:02:20Z")

</div>

The code now creates a CSV that has one line per row from my DB SQL selection. But only for the last of the 3 databases I am iterating through. Is this restriction of the sqltocsv logic or user error? cheers in advance.

---

<div class="post-metadata">

**Author:** ![John\_Denny](https://forum.golangbridge.org/user_avatar/forum.golangbridge.org/john_denny/32/7672_2.png) [@John\_Denny](https://forum.golangbridge.org/u/John_Denny)\
**Post date:** [January 8, 2019, 2:01pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/37 "2019-01-08T14:01:31Z")

</div>

Dear all, any more thoughts?

---

<div class="post-metadata">

**Author:** ![system](https://forum.golangbridge.org/uploads/default/original/2X/5/5ad234f7c3dbc68b6cc72d338ce4f2973d9fd81c.png) [@system](https://forum.golangbridge.org/u/system)\
**Post date:** [April 8, 2019, 2:01pm UTC](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955/38 "2019-04-08T14:01:33Z")

</div>

Closed on April 8, 2019, 2:01pm UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

[Previous page](https://forum.golangbridge.org/t/new-to-go-sql-to-csv/11955.md?page=1)
