github.com/jdgcs/sqlite3@v1.12.1-0.20210908114423-bc5f96e4dd51/examples/example1/main.go (about)

     1  package main
     2  
     3  import (
     4  	"database/sql"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"os"
     8  	"path/filepath"
     9  
    10  	_ "modernc.org/sqlite"
    11  )
    12  
    13  func main() {
    14  	if err := main1(); err != nil {
    15  		fmt.Println(err)
    16  		os.Exit(1)
    17  	}
    18  }
    19  
    20  func main1() error {
    21  	dir, err := ioutil.TempDir("", "test-")
    22  	if err != nil {
    23  		return err
    24  	}
    25  
    26  	defer os.RemoveAll(dir)
    27  
    28  	fn := filepath.Join(dir, "db")
    29  
    30  	db, err := sql.Open("sqlite", fn)
    31  	if err != nil {
    32  		return err
    33  	}
    34  
    35  	if _, err = db.Exec(`
    36  drop table if exists t;
    37  create table t(i);
    38  insert into t values(42), (314);
    39  `); err != nil {
    40  		return err
    41  	}
    42  
    43  	rows, err := db.Query("select 3*i from t order by i;")
    44  	if err != nil {
    45  		return err
    46  	}
    47  
    48  	for rows.Next() {
    49  		var i int
    50  		if err = rows.Scan(&i); err != nil {
    51  			return err
    52  		}
    53  
    54  		fmt.Println(i)
    55  	}
    56  
    57  	if err = rows.Err(); err != nil {
    58  		return err
    59  	}
    60  
    61  	if err = db.Close(); err != nil {
    62  		return err
    63  	}
    64  
    65  	fi, err := os.Stat(fn)
    66  	if err != nil {
    67  		return err
    68  	}
    69  
    70  	fmt.Printf("%s size: %v\n", fn, fi.Size())
    71  	return nil
    72  }