2017-03-20 3 views
0

Go言語を使用してMySQLデータベースからデータを読み込みたいとします。このスクリプトは次のようなものですMySQLからデータを選択して新しい構造体に追加してバイトに変換する方法

func GetAllCountry() []*Country{ 

    dbConnection := db.ConnectMySQL() 

    rows, err := dbConnection.Query("SELECT id, country_code, country_name, phone_code, icon FROM country;") 
    if err != nil { 
     log.Fatal(err) 
    } 
    defer rows.Close() 

    country := new(Country) 
    var countries []*Country 
    for rows.Next() { 
     err := rows.Scan(&country.id, &country.country_code, &country.country_name, &country.phone_code, &country.icon) 
     if err != nil { 
      log.Fatal(err) 
     } 
     countries = append(countries, country) 
     fmt.Println(country) 
    } 
    return countries 
} 

戻されたデータはオブジェクトStructに保存されます。構造体は次のようになります

type Country struct { 
    id    int `json:"Country.id"` 
    country_code string `json:"Country.country_code"` 
    country_name string `json:"Country.country_name"` 
    phone_code  string `json:"Country.phone_code"` 
    icon   string `json:"Country.icon"` 
} 

oherファイルでは、すべてのデータを取得する関数を作成しています。私はその関数を呼び出してから、それをMessageBrokerに送るために[]byteに変換します。ここで

[]byte

func GetCountry(msg string) []byte { 

    // country := new(countryModel.Country) 
    var countries []*countryModel.Country 

    countries = countryModel.GetAllCountry() 
    log.Println("Show result: ", countries) 

    jsResult, err := json.Marshal(countries) 

    if err != nil { 
     logger.Error(err, "Failed on GetCountry") 
    } 


    log.Println("Show result JSON: ", jsResult) 

    return jsResult 
} 

に変換する機能である。しかしGetCountry機能で返された結果は、私が欲しいものではありません。その関数で は、私は私が私のコンソール上のデータを表示

[ 
    {}, 
    {} 
] 

を取得します。

&{1 ID Indonesia +62 no-data} 
&{2 MY Malaysia +60 no-data} 
2017/03/20 17:55:27 Show result: [0xc8200ba410 0xc8200ba410] 
2017/03/20 17:55:27 Show result JSON: [91 123 125 44 123 125 93] 

助けてください。コメントで@ M-AbdelRahmanで述べたように

+0

国の構造フィールドは、大文字で始まる必要があります。 'type国struct {ID int}' –

答えて

0

は、あなたのCountry構造体のフィールドはをエクスポートする必要がアンエクスポート(で始まるものがあるフィールド上json.Marshalのでスキップを(大文字で始まるもの)小文字)、それであなたは{}に戻ります。

type Country struct { 
    Id    int `json:"Country.id"` 
    CountryCode string `json:"Country.country_code"` 
    CountryName string `json:"Country.country_name"` 
    PhoneCode  string `json:"Country.phone_code"` 
    Icon   string `json:"Country.icon"` 
} 

これに応じてスキャンを変更する必要があります。

err := rows.Scan(&country.Id, &country.CountryCode, &country.CountryName, &country.PhoneCode, &country.Icon) 
関連する問題