golang接続mssqlsqlサーバー



Golang Connect Mssql Sql Server



package main import ( 'database/sql' 'fmt' 'strings' ) import ( _ 'github.com/mattn/go-adodb' ) type Mssql struct { *sql.DB dataSource string database string windows bool sa SA } type SA struct { user string passwd string } func (m *Mssql) Open() (err error) { var conf []string conf = append(conf, 'Provider=SQLOLEDB') conf = append(conf, 'Data Source='+m.dataSource) if m.windows { // Integrated Security=SSPI This means to log in to the SQL SERVER server as the current WINDOWS system user (it needs to be set when sqlserver is installed), // If the SQL SERVER server does not support login in this way, an error will occur. conf = append(conf, 'integrated security=SSPI') } conf = append(conf, 'Initial Catalog='+m.database) conf = append(conf, 'user id='+m.sa.user) conf = append(conf, 'password='+m.sa.passwd) m.DB, err = sql.Open('adodb', strings.Join(conf, '')) if err != nil { return err } return nil } func main() { db := Mssql{ dataSource: 'CODY\SQLEXPRESS', database: 'test', // windwos: true is windows authentication, false must set sa account and password windows: true, sa: SA{ user: 'sa', passwd: '123456', }, } // Connect to the database err := db.Open() if err != nil { fmt.Println('sql open:', err) return } defer db.Close() // Execute SQL statement rows, err := db.Query('select * from info') if err != nil { fmt.Println('query: ', err) return } for rows.Next() { var name string var number int rows.Scan(&name, &number) fmt.Printf('Name: %s Number: %d ', name, number) } }

この記事は以下から来ています: CSDNブログ

ありがとう著者:CodyGuo



元のテキストを表示する: https://blog.csdn.net/CodyGuo/article/details/51014450?hmsr=studygolang.com&utm_medium=studygolang.com&utm_source=studygolang.com