O‘ZBEKISTON RESPUBLIKASI RAQAMLI TEXNALOGIYALAR VAZIRLIGI
MUHAMMAD AL-XORAZMIY NOMIDAGI
TOSHKENT AXBOROT TEXNOLOGIYALARI UNIVERSITETI SAMARQAND FILIALI
“Ma’lumotlar bazasi xavfsizligi” fanidan
1-Mustaqil ishi
Bajardi: Do’stmurodova M.
Tekshirdi: Rahmatullayev I.
SAMARQAND 2023
SELECT sql so’rovi buyrug’i bilan ishlash
Reja:
Nazariy ma’lumot
Bajarilgan ish va natijasi
Xulosa
Foydalanilgan adabiyotlar
Nazariy ma’lumot.
SQLda SELECT opratori tanlab olish uchun hizmat qiladi ya’ni ma’lumotlardagi bizga kerakli qismini yoki hammasini tanlab olib uning ustida amallar bajaramiz. Masalan students jadvali bor. Uning name, surname, email, group, phone nomli ustunlari bor. Shu jadvalning ustiga amallarni bajaramiz.
Bajarilgan ish va natijasi.
Dastlab, baza nomli loyha ochamiz va uni o’zimizga qulay code editorda ochib olamiz. Endi uni ma’lumotlar mazasiga ulashimiz kerak. Buning uchun db.go fileni yaratamiz va termonalga quyidagi komandani kiritamiz.
go get -u gorm.io/driver/mysql
db.go ichiga quidagi kodni joylaymiz.
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var db *gorm.DB
const (
DBNAME = "baza_db"
DBUSER = "root"
DBPASSWORD = ""
)
func InitDB() {
dsn := fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/%s?charset=utf8mb4&parseTime=True&loc=Local", DBUSER, DBPASSWORD, DBNAME)
var err error
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("Maʼlumotlar bazasiga ulanib boʻlmadi")
}
}
Bazaga ulanganidan keyin gin freamforkini ishlatish uchun quyidagi komandani ishga tushiramiz.
go get github.com/gin-gonic/gin
Endi ishimiz yengil bo’lishi uchun ORMdan foydalanamiz. Goda GORM nomli ORM mavjud. Uni o’rnatishimiz kerak.
go get -u gorm.io/gorm
Endi Student jadvalimizni ustunlarini belgilab qo’yamiz. Uning uchun godagi struct dan foydalanzmiz.
type Student struct {
ID uint `gorm:"primaryKey" json:"id"`
Name string `json:"name"`
Surname string `json:"surname"`
Email string `json:"email"`
Group int `json:"group"`
Phone int `json:"phone"`
}
So’ng Loyhamizni asosiy CRUD funksiyalarini yozami.
func GetAllStudents() ([]Student, error) {
var users []Student
err := db.Find(&users).Error
return users, err
}
func GetStudentByID(id uint) (*Student, error) {
var user Student
err := db.First(&user, id).Error
if err != nil {
return nil, err
}
return &user, nil
}
func CreateStudent(user *Student) error {
return db.Create(&user).Error
}
func UpdateStudent(user *Student) error {
return db.Save(&user).Error
}
func DeleteStudent(id uint) error {
return db.Delete(&Student{}, id).Error
}
Keyin main funksiyamizda hamma funksiyalarni chaqiramiz.
package main
import (
"github.com/gin-gonic/gin"
"strconv"
)
func main() {
InitDB()
r := gin.Default()
r.GET("/api/v1/students", func(c *gin.Context) {
users, err := GetAllStudents()
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
c.JSON(200, users)
})
r.GET("/api/v1/student/:id", func(c *gin.Context) {
idStr := c.Param("id")
idInt, err := strconv.Atoi(idStr)
if err != nil {
c.JSON(400, gin.H{"error": "Invalid user ID"})
return
}
user, err := GetStudentByID(uint(idInt))
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
c.JSON(200, user)
})
r.POST("/api/v1/student", func(c *gin.Context) {
var user Student
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
if err := CreateStudent(&user); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
c.JSON(200, user)
})
r.PUT("/api/v1/student/:id", func(c *gin.Context) {
// URL orqali foydalanuvchi identifikatorini olish
userID := c.Param("id")
userIDInt, err := strconv.Atoi(userID)
if err != nil {
c.JSON(400, gin.H{"error": "Noto'g'ri foydalanuvchi identifikatori"})
return
}
existingUser, err := GetStudentByID(uint(userIDInt))
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
var newUser Student
if err := c.ShouldBindJSON(&newUser); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
existingUser.Name = newUser.Name
existingUser.Surname = newUser.Surname
existingUser.Email = newUser.Email
existingUser.Email = newUser.Email
existingUser.Group = newUser.Group
existingUser.Phone = newUser.Phone
if err := UpdateStudent(existingUser); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
c.JSON(200, existingUser)
})
r.DELETE("/api/v1/student/:id", func(c *gin.Context) {
idStr := c.Param("id")
idInt, err := strconv.Atoi(idStr)
if err != nil {
c.JSON(400, gin.H{"error": "Invalid user ID"})
return
}
if err := DeleteStudent(uint(idInt)); err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{"message": "User deleted successfully"})
})
r.Run(":8080")
}
Xulosa.
Oddiy CRUD amalini go dasturlash tilida ko’rib chiqdiq. Buning SQL kodidan foydalanmagan bo’lsakda ORM (Object Relational Mapping) bunda SQLning hamma ishini bajarsa bo’ladi. Shuningdak SQLda yo’lga qo’yadigan xató va kamchiliklarimizni ham bartaraf etadi. Lekin ORM ning backgroundida SQL kodlari yotadi.
Foydalanilgan adabiyotlar
1) https://app.programmer.uz/course/go-dasturlash-tili
|