-- Go

Go Database #1 : Go ile Temel Veritabanı İşlemleri

Merhabalar,

GO programlama dili maceralarına veritabanı işlemleriyle devam ediyoruz. Bu makale ve video eğitimde GO programlama dilini kullanarak MySQL veritabanı üzerinde SELECT, INSERT, DELETE gibi işlemleri birden fazla yöntem kullanarak gerçekleştireceğiz.

Makalede video içerisinde anlattığım gibi uzun uzun anlatmak yerine sadece kodları paylaşacağım. Videoyu izleyip bu makaledeki kodları inceleyebilirsiniz.

Video Eğitim; https://youtu.be/DnB-s1pgGbc

Kodlar;

package main

import (
	"database/sql"

	_ "github.com/go-sql-driver/mysql"
)

func main() {

	db, err := sql.Open("mysql", "root:1234567@/demodb")
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()

	/**/
	var (
		//	ID        int
		Username  string
		Email     string
		Password  string
		FirstName string
		LastName  string
		BirthDate string
		IsActive  bool
	)

	/*
	  CREATE TABLE `users` (
	  `ID` int(11) NOT NULL AUTO_INCREMENT,
	  `Username` varchar(45) NOT NULL,
	  `Email` varchar(45) NOT NULL,
	  `Password` varchar(45) NOT NULL,
	  `FirstName` varchar(45) NOT NULL,
	  `LastName` varchar(45) NOT NULL,
	  `BirthDate` varchar(45) DEFAULT NULL,
	  `IsActive` tinyint(1) DEFAULT NULL,
	  PRIMARY KEY (`ID`),
	  UNIQUE KEY `ID_UNIQUE` (`ID`)
	  ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
	*/

	/*
			createStatement := "`users`(`ID` int(11) NOT NULL AUTO_INCREMENT, `Username` varchar(45) NOT NULL, `Email` varchar(45) NOT NULL, `Password` varchar(45) NOT NULL, `FirstName` varchar(45) NOT NULL, `LastName` varchar(45) NOT NULL, `BirthDate` varchar(45) DEFAULT NULL, `IsActive` tinyint(1) DEFAULT NULL, PRIMARY KEY(`ID`), UNIQUE KEY `ID_UNIQUE`(`ID`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;"

			_, err = db.Exec("CREATE TABLE IF NOT EXISTS " + createStatement)
			if err != nil {
				log.Fatal(err)
			}

			// Veri Ekleme
			res, err := db.Exec("INSERT INTO users(Username, Email, Password, FirstName, LastName, BirthDate, IsActive) VALUES('Deneme1', '12345!','deneme@dene.com','Cihan','Özhan','2017.1.1', 1)")
			if err != nil {
				log.Fatal(err)
			}
			rowCount, err := res.RowsAffected()
			if err != nil {
				log.Fatal(err)
			}
			log.Printf("Inserted %d rows", rowCount)

			lastID, err1 := res.LastInsertId()
			if err1 != nil {
				log.Fatal(err1)
			}
			log.Printf("Inserted ID : %d", lastID)

		// Eklenen kayıtları getir.
		rows, err := db.Query("SELECT * FROM users")
		if err != nil {
			log.Fatal(err)
		}

		// rows.Columns()

		for rows.Next() {
			err = rows.Scan(&ID, &Username, &Email, &Password, &FirstName, &LastName, &BirthDate, &IsActive)
			if err != nil {
				log.Fatal(err)
			}
			log.Printf("Bulunan satır içeriği : %q", strconv.Itoa(ID)+" "+Username+" "+Email+" "+Password+" "+FirstName+" "+LastName+" "+BirthDate+" "+strconv.FormatBool(IsActive))
		}
		// alternatif
		if err = rows.Err(); err != nil {
			log.Fatal(err)
		}
		rows.Close()
	*/

	// .........

	/*
		rows, errQ := db.Query("SELECT * FROM users WHERE ID = ?", 12)
		if errQ != nil {
			log.Fatal(errQ)
		}
		defer rows.Close()
		for rows.Next() {
			err = rows.Scan(&ID, &Username, &Email, &Password, &FirstName, &LastName, &BirthDate, &IsActive)
			if err != nil {
				log.Fatal(err)
			}
			log.Printf("Bulunan satır içeriği : %q", strconv.Itoa(ID)+" "+Username+" "+Email+" "+Password+" "+FirstName+" "+LastName+" "+BirthDate+" "+strconv.FormatBool(IsActive))
		}
		errQ = rows.Err()
		if errQ != nil {
			log.Fatal(errQ)
		}
	*/

	// .........

	/*
		err = db.QueryRow("SELECT * FROM users limit 1").Scan(&ID, &Username, &Email, &Password, &FirstName, &LastName, &BirthDate, &IsActive)
		if err != nil {
			if err == sql.ErrNoRows {
				// kayıt yoksa, yapılacak işler
			} else {
				log.Fatal(err)
			}
		}
		//log.Println("Bir satır bulundu : ", Username)
		log.Printf("Bulunan satır içeriği : %q", strconv.Itoa(ID)+" "+Username+" "+Email+" "+Password+" "+FirstName+" "+LastName+" "+BirthDate+" "+strconv.FormatBool(IsActive))
	*/

	// .........

	// Multiple Active Result Set : MARS

	// _, err := db.Exec("DELETE FROM xTable1; DELETE FROM xTable2")

	// Preparing Queries

	/*
		stmt, errQ := db.Prepare("SELECT * FROM users WHERE ID = ?")
		if errQ != nil {
			log.Fatal(errQ)
		}
		defer stmt.Close()
		rows, errX := stmt.Query(1)
		if errX != nil {
			log.Fatal(errX)
		}
		defer rows.Close()
		for rows.Next() {
			scanErr := rows.Scan(&ID, &Username, &Email, &Password, &FirstName, &LastName, &BirthDate, &IsActive)
			if scanErr != nil {
				log.Fatal(scanErr)
			}
			log.Printf("Bulunan satır içeriği : %q", strconv.Itoa(ID)+" "+Username+" "+Email+" "+Password+" "+FirstName+" "+LastName+" "+BirthDate+" "+strconv.FormatBool(IsActive))
		}
	*/

	// Preparing Query - Single rows

	/*
		stmt, errQ := db.Prepare("SELECT * FROM users WHERE ID = ?")
		if errQ != nil {
			log.Fatal(errQ)
		}
		errX := stmt.QueryRow(3).Scan(&ID, &Username, &Email, &Password, &FirstName, &LastName, &BirthDate, &IsActive)
		if errX != nil {
			log.Fatal(errX)
		}
		fmt.Println(FirstName + " " + LastName)
	*/

	// ----------------

	// Modifying Data

	/*
		res, _ := db.Exec("DELETE FROM users LIMIT 1")
		rowCount, _ := res.RowsAffected()
		fmt.Println(rowCount)
		lastID, _ := res.LastInsertId()
		fmt.Println(lastID)
	*/

	// Insert İşlemi

	/*
		stmt, err := db.Prepare("INSERT INTO users(Username, Email, Password, FirstName, LastName, BirthDate, IsActive) VALUES(?, ?, ?, ?, ?, ?, ?)")
		Username = "CO"
		Email = "abc@xyz.co"
		Password = "1234!"
		FirstName = "ABC"
		LastName = "XYZ"
		BirthDate = "2017.1.2"
		IsActive = true
		res, errStmt := stmt.Exec(Username, Email, Password, FirstName, LastName, BirthDate, IsActive)
		if errStmt != nil {
			log.Fatal(errStmt)
		}
		fmt.Println(res.LastInsertId())
	*/

	// Transaction

	/*
		tx, errTx := db.Begin()
		// ...
		_, errTx = db.Exec("Update ....", args)
		// ...
		if errTx != nil {
			log.Fatal(errTx)
			tx.Rollback()
		}
		// ...
		errTx = tx.Commit()
	*/
}

İyi çalışmalar.
Cihan Özhan

Yorumla

Yorum