2、基于ARM平台Golang简单Demo:使用sqlite3数据库

arm平台为M3352核心板。

编译环境为Ubuntu14.04

目标:在Ubuntu环境编译Go代码,在arm平台运行,使用sqlite3数据库

源代码文件名:main.go

package main

import (
	"database/sql"
	"fmt"
	_ "github.com/mattn/go-sqlite3-master"
	"os"
)

func main(){
	//creat database
	db,err := sql.Open("sqlite3","./MyDatabase.db")
	if err != nil {
		fmt.Fprintf(os.Stderr, "Open database: %v\n", err)
		os.Exit(1)
	}

	//creat table
	sql := "CREATE TABLE STUDENTS(ID INT PRIMARY KEY     NOT NULL, NAME           TEXT    NOT NULL,AGE            INT     NOT NULL);"
	_,err = db.Exec(sql)
	if err != nil{
		fmt.Fprintf(os.Stderr, "Creat Table: %v\n", err)
		os.Exit(1)
	}

	//insert
	sql = "INSERT INTO STUDENTS (ID,NAME,AGE) VALUES (1, 'LiLi', 15);INSERT INTO STUDENTS (ID,NAME,AGE) VALUES (2, 'Lucy', 16); "
	_,err = db.Exec(sql)
	if err != nil{
		fmt.Fprintf(os.Stderr, "Insert: %v\n", err)
		os.Exit(1)
	}

	//select
	rows,err := db.Query("SELECT * FROM STUDENTS")
	if err != nil{
		fmt.Fprintf(os.Stderr, "Select: %v\n", err)
		os.Exit(1)
	}
	for rows.Next(){
		var id int
		var name string
		var age int
		err := rows.Scan(&id,&name,&age)
		if err != nil{
			fmt.Fprintf(os.Stderr, "Select Rows: %v\n", err)
			os.Exit(1)
		}
		fmt.Println(id,name,age)
	}

	//delete
	_,err =  db.Exec("DELETE FROM STUDENTS WHERE ID=1")
	if err != nil{
		fmt.Fprintf(os.Stderr, "Delete: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("End")
}

编译指令:

CGO_ENABLED=1 GOARCH=arm CC=arm-none-linux-gnueabi-gcc go build main.go 

执行结果:

[root@M3352 test]# ./main
1 LiLi 15
2 Lucy 16
End
[root@M3352 test]#

查看数据库MyDatabase.db,可发现数据已经正常写入。

你可能感兴趣的:(Go,Golang,ARM)