当前位置: 首页>>代码示例>>Golang>>正文


Golang DB.Close方法代码示例

本文整理汇总了Golang中github.com/jinzhu/gorm.DB.Close方法的典型用法代码示例。如果您正苦于以下问题:Golang DB.Close方法的具体用法?Golang DB.Close怎么用?Golang DB.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在github.com/jinzhu/gorm.DB的用法示例。


在下文中一共展示了DB.Close方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: createTables

func createTables(db *gorm.DB, values ...interface{}) error {
	for _, value := range values {
		if !db.HasTable(value) {
			err := db.CreateTable(value).Error
			if err != nil {
				errClose := db.Close()
				if errClose != nil {
					fmt.Printf("%s", errClose)
				}
				return err
			}
		}
	}
	return nil
}
开发者ID:ReanGD,项目名称:go-web-search,代码行数:15,代码来源:content.go

示例2: main

func main() {
	var db gorm.DB
	var err error

	db, err = gorm.Open("mysql", "root:[email protected](10.0.1.31:3306)/osinstall?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer db.Close()

	//db.SingularTable(true)
	err = initdb.DropOsInstallTables(&db, nil)
	err = initdb.InitOsInstallTables(&db, nil)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println("done")
}
开发者ID:lue828,项目名称:osinstall-server,代码行数:20,代码来源:main.go

示例3: dbCloseOpen

func dbCloseOpen(prevDb *gorm.DB) (*gorm.DB, error) {
	prevDb.Close()
	return dbOpen()
}
开发者ID:gnewton,项目名称:GoPubMed2SQLite3,代码行数:4,代码来源:db.go

示例4:

		api = api2go.NewAPIWithBaseURL("v0", "http://localhost:31415")
		var err error
		db, err = storage.InitDB()
		if err != nil {
			panic(err)
		}
		userStorage := storage.NewUserStorage(db)
		chocStorage := storage.NewChocolateStorage(db)
		api.AddResource(model.User{}, resource.UserResource{ChocStorage: chocStorage, UserStorage: userStorage})
		api.AddResource(model.Chocolate{}, resource.ChocolateResource{ChocStorage: chocStorage, UserStorage: userStorage})
		rec = httptest.NewRecorder()
	})
	AfterEach(func() {
		db.Exec("DROP TABLE chocolates")
		db.Exec("DROP TABLE users")
		db.Close()
	})

	var createUser = func() {
		rec = httptest.NewRecorder()
		req, err := http.NewRequest("POST", "/v0/users", strings.NewReader(`
		{
			"data": {
				"type": "users",
				"attributes": {
					"user-name": "marvin"
				}
			}
		}
		`))
		Expect(err).ToNot(HaveOccurred())
开发者ID:hnakamur,项目名称:api2go-gorm-gin-crud-example,代码行数:31,代码来源:crud_example_test.go

示例5: main

func main() {
	// --------------------------------------------------------------------
	// Parse flags
	// --------------------------------------------------------------------
	var configFilePath string
	var printConfig bool
	var migrateDB bool
	var scheduler *remoteworkitem.Scheduler
	flag.StringVar(&configFilePath, "config", "", "Path to the config file to read")
	flag.BoolVar(&printConfig, "printConfig", false, "Prints the config (including merged environment variables) and exits")
	flag.BoolVar(&migrateDB, "migrateDatabase", false, "Migrates the database to the newest version and exits.")
	flag.Parse()

	// Override default -config switch with environment variable only if -config switch was
	// not explicitly given via the command line.
	configSwitchIsSet := false
	flag.Visit(func(f *flag.Flag) {
		if f.Name == "config" {
			configSwitchIsSet = true
		}
	})
	if !configSwitchIsSet {
		if envConfigPath, ok := os.LookupEnv("ALMIGHTY_CONFIG_FILE_PATH"); ok {
			configFilePath = envConfigPath
		}
	}

	var err error
	if err = configuration.Setup(configFilePath); err != nil {
		logrus.Panic(nil, map[string]interface{}{
			"configFilePath": configFilePath,
			"err":            err,
		}, "failed to setup the configuration")
	}

	if printConfig {
		os.Exit(0)
	}

	// Initialized developer mode flag for the logger
	log.InitializeLogger(configuration.IsPostgresDeveloperModeEnabled())

	printUserInfo()

	var db *gorm.DB
	for {
		db, err = gorm.Open("postgres", configuration.GetPostgresConfigString())
		if err != nil {
			db.Close()
			log.Logger().Errorf("ERROR: Unable to open connection to database %v\n", err)
			log.Logger().Infof("Retrying to connect in %v...\n", configuration.GetPostgresConnectionRetrySleep())
			time.Sleep(configuration.GetPostgresConnectionRetrySleep())
		} else {
			defer db.Close()
			break
		}
	}

	if configuration.IsPostgresDeveloperModeEnabled() {
		db = db.Debug()
	}

	// Migrate the schema
	err = migration.Migrate(db.DB())
	if err != nil {
		log.Panic(nil, map[string]interface{}{
			"err": fmt.Sprintf("%+v", err),
		}, "failed migration")
	}

	// Nothing to here except exit, since the migration is already performed.
	if migrateDB {
		os.Exit(0)
	}

	// Make sure the database is populated with the correct types (e.g. bug etc.)
	if configuration.GetPopulateCommonTypes() {
		// set a random request ID for the context
		ctx, req_id := client.ContextWithRequestID(context.Background())
		log.Debug(ctx, nil, "Initializing the population of the database... Request ID: %v", req_id)

		if err := models.Transactional(db, func(tx *gorm.DB) error {
			return migration.PopulateCommonTypes(ctx, tx, workitem.NewWorkItemTypeRepository(tx))
		}); err != nil {
			log.Panic(ctx, map[string]interface{}{
				"err": fmt.Sprintf("%+v", err),
			}, "failed to populate common types")
		}
		if err := models.Transactional(db, func(tx *gorm.DB) error {
			return migration.BootstrapWorkItemLinking(ctx, link.NewWorkItemLinkCategoryRepository(tx), link.NewWorkItemLinkTypeRepository(tx))
		}); err != nil {
			log.Panic(ctx, map[string]interface{}{
				"err": fmt.Sprintf("%+v", err),
			}, "failed to bootstap work item linking")
		}
	}

	// Scheduler to fetch and import remote tracker items
	scheduler = remoteworkitem.NewScheduler(db)
	defer scheduler.Stop()
//.........这里部分代码省略.........
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:101,代码来源:main.go

示例6: Monitor

// Monitor bind and monitor for DNS packets. This will also
// handle the various output methods.
func Monitor(options *Options) {

	if !options.Quiet {
		fmt.Printf("\n %s (%s) - %s\n\n",
			Name,
			Version,
			Description,
		)

		fmt.Printf(" Hostname: %s\n", options.Hostname)

		fmt.Printf(" Interface: %s (%s)\n",
			options.InterfaceData.Name, options.InterfaceData.HardwareAddr.String())

		fmt.Printf(" IP Address: %s\n", options.Ip)

		// addrs, err := options.InterfaceData.Addrs()

		// if err == nil {
		// var list []string

		// for _, addr := range addrs {
		// list = append(list, addr.String())
		// }

		// fmt.Printf(" Addresses: %s\n\n", strings.Join(list, ", "))
		// } else {
		// fmt.Printf("\n")
		// }
	}

	expr := fmt.Sprintf("port %d", options.Port)

	h, err := pcap.OpenLive(options.Interface, int32(snaplen), true, 500)

	if h == nil {
		fmt.Fprintf(os.Stderr, "%s Error: %s\n", Name, err)
		os.Exit(-1)
	}

	ferr := h.SetFilter(expr)

	if ferr != nil {
		fmt.Fprintf(os.Stderr, "%s Error: %s", Name, ferr)
		os.Exit(-1)
	}

	var file *os.File

	if options.Write != "" {
		file = OpenFile(options.Write)

		defer func() {
			if err := file.Close(); err != nil {
				panic(err)
			}
		}()
	}

	var db gorm.DB
	var clientId int64 = 0

	queue := make(chan *Question)

	if options.Mysql || options.Postgres || options.Sqlite3 {

		db, err = DatabaseConnect(options)

		if err != nil {
			fmt.Println("\n Error: ", err.Error(), "\n")
			os.Exit(1)
		}

		clientId = CreateClient(db, options)

		go func() {
			for elem := range queue {
				elem.ToDatabase(db, options)
			}
		}()
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {

		defer func() {
			if r := recover(); r != nil {
				fmt.Println("DB Queue - Recovered:", r)
				fmt.Println("Please report this issue. https://github.com/mephux/dnas")
			}
		}()

		for sig := range c {
			if sig.String() == "interrupt" {
				file.Close()
				close(queue)

//.........这里部分代码省略.........
开发者ID:mehulsbhatt,项目名称:dnas,代码行数:101,代码来源:monitor.go


注:本文中的github.com/jinzhu/gorm.DB.Close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。