golang working with sql server
Golang ORM for Mssql server can be found here (GORM) and here :-
Here is the code that i used to fetch data from a table called country which has just 2 columns which are :-
a) countryid
b) countryname
Here is the code that i used to access my sql server using GORM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"github.com/jinzhu/gorm" | |
_ "github.com/jinzhu/gorm/dialects/mssql" | |
) | |
func main() { | |
db, _ := gorm.Open("mssql", "sqlserver://sa:P@ssword01@192.168.99.100:1433?database=pts") | |
var ( | |
countryid int | |
sqlversion string | |
) | |
rows, _ := db.Raw("select * from country").Rows() // (*sql.Rows, error) | |
defer rows.Close() | |
for rows.Next() { | |
rows.Scan(&countryid, &sqlversion) | |
log.Println(countryid, sqlversion) | |
} | |
defer db.Close() | |
} |
Here is the code that i used to access my mssql server docker running on 192.168.99.100 and database called PTS.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"fmt" | |
"log" | |
_ "github.com/denisenkom/go-mssqldb" | |
) | |
func main() { | |
condb, errdb := sql.Open("mssql", "server=192.168.99.100;database=pts;user id=sa;password=P@ssword01;") | |
if errdb != nil { | |
fmt.Println(" Error open db:", errdb.Error()) | |
} | |
var ( | |
countryid int | |
sqlversion string | |
) | |
rows, err := condb.Query("select * from country") | |
if err != nil { | |
log.Fatal(err) | |
} | |
for rows.Next() { | |
err := rows.Scan(&countryid, &sqlversion) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Println(sqlversion) | |
} | |
defer condb.Close() | |
} |
Comments