SlideShare a Scribd company logo
Golang
Web
Database
Database
● Go doesn't provide any database drivers, but it does have a driver interface defined in the
database/sql package
– The advantage is that if your code is developed according to these interface standards, you will not
need to change any code if your database changes.
● We always see the following code when we use third-party drivers:
– Import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
– Here the underscore (also known as a 'blank') “_”:
● “_” được dùng trong các hàm (func) lúc trả về các giá trị mà chúng ta không cần thì chúng ta sẽ loại bỏ nó (discarding)
Khi bạn import một thư viện thì bạn sẽ phải dùng tất cả các package đó (nếu không dùng package đó trong đoạn code nào đó thì Go
sẽ biên dịch và cảnh báo lại).
→ khi sử dụng underscore “_” khi import thư viện thì có nghĩa là bạn chỉ cần dùng function init() mà không cần sử dụng trực tiếp
→ tính năng này cần thiết cho registering database drivers vì nó sẽ tự động đăng ký database drivers mà không cần phải gọi nó
Database
● Function:
– sql.Register(): registering database drivers when you use
third-party database drivers.
● Gọi hàm này trong hàm init()
– driver.Driver: is an interface containing an Open(name
string) method that returns a Conn interface.
– driver.Conn: This is a database connection interface with
some methods the same Conn can only be used in one goroutine.
– driver.Stmt
– driver.Tx
Database
● Quy trình:
– Step 0: Importing a Database Driver
● L y package:ấ
– go get github.com/go-sql-driver/mysql
● Import trong mã ngu nồ
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
Database
● Quy trình:
– Step 1: s d ngử ụ sql.Open đ chu n b k t n iể ẩ ị ế ố
● db, err := sql.Open(<driver name>, <command_to_connect>)
– <command_to_connect>: driver-specific syntax that tells the driver how to
access the underlying datastore
– Giá tr tr v : c n ki m traị ả ề ầ ể handle errors
● Ví d :ụ
– db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/hello")
– db, err := sql.Open("mysql", "<user>:<password>@/test?charset=utf8")
● Sql.Open ch a t o k t n i ngayư ạ ế ố
– Nó t o k t n i ch khi nào có yêu c u (query) đ u tiên.ạ ế ố ỉ ầ ầ
– db.Ping() dùng đ ki m tra database is available and accessible (forể ể
example, check that you can establish a network connection and log in)
Database
● Quy trình:
– Step 2: T o m i d li u, g m 3 b c:ạ ớ ữ ệ ồ ướ
● stmt, err := db.Prepare(<command>): chu n b đ nh d ng d li u đ chèn vào DBẩ ị ị ạ ữ ệ ể
– returns a SQL operation that is going to be executed. It also returns the execution status after executing SQL.
– db là giá tr tr v t hàm slq.Open()ị ả ề ừ
– Ví d : db.Prepare("INSERT userinfo SETụ username=?,departname=?,created=?")
● res, err := stmt.Exec(<data>): th c hi n l nhự ệ ệ
– Stmt là giá tr tr v t hàm db.Prepare()ị ả ề ừ
– <data>: là m u chu n theo th t đã xác đ nh trên b c chu n b trênẫ ẩ ứ ự ị ướ ẩ ị
– Ví d : stmt.Exec("astaxie", "a72", "2016-12-09") → tuân theo chu n <username,departname,created> trênụ ẩ ở
● res.<Action>: đ c giá tr tr v sau khi th c hi n l nhọ ị ả ề ự ệ ệ
– res là giá tr tr v t hàmị ả ề ừ stmt.Exec()
– Có các Action khác nhau:
● id, err := res.LastInsertId()
● affect, err := res.RowsAffected()
Database
● Quy trình:
– Step 3: Truy v n tìm ki m d li uấ ế ữ ệ
● L nh truy v n:ệ ấ db.Query(<command_to_query>)
– rows, err := db.Query("SELECT * FROM userinfo")
● Duy t danh sách tr v :ệ ả ề
– rows.Next():
– rows.Scan(): read the columns in each row into variables
● defer rows.Close(): đóng rows
for rows.Next() { → l y l n l t các row tr vấ ầ ượ ả ề
err = rows.Scan(&uid, &username, &department, &created)
}
Database
● Quy trình:
– Step 4: Xóa d li u (t ng t nh Step2)ữ ệ ươ ự ư
● stmt, err = db.Prepare(<command_to_del>)
– <command_to_del>: là l nh mysql đ xóa d li uệ ể ữ ệ
– stmt, err = db.Prepare("delete from userinfo where uid=?")
● res, err = stmt.Exec(id)
– Stmt thi u giá tr d li uế ị ữ ệ id nên l nh này đ a id vào và th c thiệ ư ự
l nh xóaệ
● affect, err = res.RowsAffected()
Note that we use the format =? to pass arguments. This
is necessary for preventing SQL injection attacks.
Database
●
Ví d đ c DB Mysql:ụ ọ
– K t n i:ế ố
●
db, err := sql.Open("mysql", "astaxie:astaxie@/test?charset=utf8")
● db.Close()
– Ghi d li u:ữ ệ
● stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
● res, err := stmt.Exec("jace", "jace in corp", "2015-12-09")
● id, err := res.LastInsertId() → ki m ch ng l n ghi d li u v a r iể ứ ầ ữ ệ ừ ồ
– C p nh p/S a d li uậ ậ ử ữ ệ
●
stmt, err = db.Prepare("update userinfo set username=? where uid=?")
●
res, err = stmt.Exec("astaxieupdate", id)
● affect, err := res.RowsAffected() → ki m ch ng l nh update có đúng đ i t ng (rows)ể ứ ệ ố ượ
– Tìm ki m d li u:ế ữ ệ
● rows, err := db.Query("SELECT * FROM userinfo")
● for rows.Next() {err = rows.Scan(&uid, &username, &department, &created)}
– Xóa d li u:ữ ệ
● stmt, err = db.Prepare("delete from userinfo where uid=?")
●
res, err = stmt.Exec(id) → th c thi l nh xóaự ệ
● affect, err = res.RowsAffected() → ki m ch ng l nh xóa có đúng đ i t ng khôngể ứ ệ ố ượ
Database
● Làm vi c v i Redisệ ớ
– redis is a key-value storage system like Memcached, that
supports the string, list, set and zset(ordered set) value types.
– Download: http://redis.io/download
– Cài đ t và th nghi m:ặ ử ệ
● Ch y server: src/redis-serverạ
● T ng tác, thao tác d li u v i server: src/redis-cliươ ữ ệ ớ
– set foo bar
– get foo
– L y th vi n database driver:ấ ư ệ
● go get github.com/astaxie/goredis
Database
● Làm vi c v i Redisệ ớ
– Các th vi n giao ti p v i redis:ư ệ ế ớ
● https://github.com/fzzy/radix
● https://github.com/alphazero/Go-Redis
– Current status is compatible with Redis 2.4.n (2.4.9 tested) and Go 1
– đã lâu không có b n c p nh tả ậ ậ
● https://github.com/simonz05/godis → b n c p nh t đã khá cũ (2012)ả ậ ậ
● https://github.com/hoisie/redis → Designed for Redis 2.6.x.
● https://github.com/garyburd/redigo
– B n m i nh t vào Tháng 5/2016ả ớ ấ
–
Database
● Làm vi c v i Redis:ệ ớ
– M t s ví d t ng tác v i Redis:ộ ố ụ ươ ớ
● https://github.com/ovr/go-redis
● https://github.com/wen866595/gredis
● https://github.com/hongruiqi/redis.go
●
cookies
●
Cookies g m các tr ng:ồ ườ
– Name: string
– Value: string
– Path: string
– Domain: string
– Expires: time.Time
– RawExpires: string
– MaxAge: int
– Secure: bool
– HttpOnly: bool
– Raw: string
– Unparsed: []string
●
Go uses the SetCookie function in the net/http package to set cookies:
– http.SetCookie(w ResponseWriter, cookie *Cookie)
– Hàm này có th dùng cho c 2 tr ng h p t o cookies và xóa cookies.ể ả ườ ợ ạ
cookies
func login(w http.ResponseWriter, r *http.Request) {
SetCookie(w)
}
login là 1 Handler c a web.ủ
Hàm Setcookie s d ng ReponseWriter đ tr v cho clientử ụ ể ả ề
func sayhelloName(w http.ResponseWriter, r *http.Request) {
GetCookie(r)
}
sayhelloName là 1 Handler c a webủ
Hàm Getcookie s d ng Request do nh n các thông s t clientử ụ ậ ố ừ
cookies
func SetCookie(res http.ResponseWriter) {
expiration := time.Now().Add(365 * 24 * time.Hour)
cookie := http.Cookie{
Name: "my-cookie",
Value: "COOKIE MONSTER",
Expires: expiration}
http.SetCookie(res, &cookie)
}
func GetCookie(req *http.Request) {
cookie, err := req.Cookie("my-cookie")
if err == nil {
fmt.Println("has cookie")
fmt.Println("get cookie")
fmt.Println(cookie)
fmt.Println(cookie.Value)
fmt.Println(cookie.Expires)
} else{
fmt.Println("please set cookie")
fmt.Println(err)
}
}
func ClearCookie(res http.ResponseWriter) {
cookie := http.Cookie{
Name: "my-cookie",
Value: "COOKIE MONSTER",
MaxAge: -1}
http.SetCookie(res, &cookie)
}
Session
● https://github.com/MorpheusXAUT/eveauth
– Có các th vi n c n thi t v thao tác sessionư ệ ầ ế ề
● https://github.com/icza/session
– Th vi n v i các ch ng năng qu n lý session kháư ệ ớ ứ ả
h u d ngữ ụ
Network service
●
we need an IP address and port number to have a unique socket.
●
TCP socket
– TCPConn struct đ mô t 1 k t n i socket.ể ả ế ố
● TCPConn can be used by either client or server for reading and writing data.
– after a connection is established, the server has the same type of connection object for the
current connection → c phía client và server cùng có 1 object đ mô t k t n i.ả ể ả ế ố
– clients send requests to servers through a TCPConn and receive information from the server
response
– servers read and parse client requests, then return feedback
● two key functions:
– func (c *TCPConn) Write(b []byte) (n int, err os.Error)
– func (c *TCPConn) Read(b []byte) (n int, err os.Error)
– TCPAddr struct to represent TCP address information:
● ResolveTCPAddr function to get a TCPAddr
Network service
● T o k t n i TCP:ạ ế ố
– DialTCP function in the net package to create a
TCP connection
● returns a TCPConn object
● func DialTCP(net string, laddr, raddr *TCPAddr) (c
*TCPConn, err os.Error)
–
Tham kh oả
● https://github.com/suyesh/go_training
●
Ad

More Related Content

Similar to Golang web database3 (20)

Báo cáo tuần đồ án
Báo cáo tuần đồ ánBáo cáo tuần đồ án
Báo cáo tuần đồ án
Lưu Việt Tùng
 
Giao trinh java script
Giao trinh java scriptGiao trinh java script
Giao trinh java script
Toàn Trần Mạnh
 
Lập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biếnLập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biến
Son Nguyen
 
Map reduce hdfs
Map reduce hdfsMap reduce hdfs
Map reduce hdfs
hoangnguyentien
 
Kiến thức cần thiết làm việc
Kiến thức cần thiết làm việcKiến thức cần thiết làm việc
Kiến thức cần thiết làm việc
manhvokiem
 
Javascript tong-hop a-z
Javascript tong-hop a-zJavascript tong-hop a-z
Javascript tong-hop a-z
Manhh Nguyễn
 
Qtu.vn sql - chuong 7
Qtu.vn  sql - chuong 7Qtu.vn  sql - chuong 7
Qtu.vn sql - chuong 7
Hoang le Minh
 
E learning lab - Tim hieu Cake PHP
E learning lab - Tim hieu Cake PHPE learning lab - Tim hieu Cake PHP
E learning lab - Tim hieu Cake PHP
elearninglabvn
 
Chuyên đề ngôn ngữ lập trình auto it
Chuyên đề ngôn ngữ lập trình auto itChuyên đề ngôn ngữ lập trình auto it
Chuyên đề ngôn ngữ lập trình auto it
bamboosky4991
 
Hadoop, HBase and Zookeeper at Tamtay
Hadoop, HBase and Zookeeper at TamtayHadoop, HBase and Zookeeper at Tamtay
Hadoop, HBase and Zookeeper at Tamtay
Eddie Bui
 
Javascript for php developer
Javascript for php developerJavascript for php developer
Javascript for php developer
Dang Tuan
 
Speaker dang minh tuan javascript for php developer
Speaker dang minh tuan   javascript for php developerSpeaker dang minh tuan   javascript for php developer
Speaker dang minh tuan javascript for php developer
AiTi Education
 
Python moi
Python moiPython moi
Python moi
DÉp LÊ
 
The Art of Readable Code - DongPV
The Art of Readable Code - DongPVThe Art of Readable Code - DongPV
The Art of Readable Code - DongPV
Đông Đô
 
Bài giảng ngôn ngữ lập trình hiện nay: Ngôn ngữ Python
Bài giảng ngôn ngữ lập trình hiện nay: Ngôn ngữ PythonBài giảng ngôn ngữ lập trình hiện nay: Ngôn ngữ Python
Bài giảng ngôn ngữ lập trình hiện nay: Ngôn ngữ Python
dtmanh1
 
Bài giảng ngôn ngữ lập trình hiện nay: Python
Bài giảng ngôn ngữ lập trình hiện nay: PythonBài giảng ngôn ngữ lập trình hiện nay: Python
Bài giảng ngôn ngữ lập trình hiện nay: Python
dtmanh1
 
Technical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vnTechnical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vn
Asahina Infotech
 
Lập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biếnLập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biến
Son Nguyen
 
Kiến thức cần thiết làm việc
Kiến thức cần thiết làm việcKiến thức cần thiết làm việc
Kiến thức cần thiết làm việc
manhvokiem
 
Javascript tong-hop a-z
Javascript tong-hop a-zJavascript tong-hop a-z
Javascript tong-hop a-z
Manhh Nguyễn
 
Qtu.vn sql - chuong 7
Qtu.vn  sql - chuong 7Qtu.vn  sql - chuong 7
Qtu.vn sql - chuong 7
Hoang le Minh
 
E learning lab - Tim hieu Cake PHP
E learning lab - Tim hieu Cake PHPE learning lab - Tim hieu Cake PHP
E learning lab - Tim hieu Cake PHP
elearninglabvn
 
Chuyên đề ngôn ngữ lập trình auto it
Chuyên đề ngôn ngữ lập trình auto itChuyên đề ngôn ngữ lập trình auto it
Chuyên đề ngôn ngữ lập trình auto it
bamboosky4991
 
Hadoop, HBase and Zookeeper at Tamtay
Hadoop, HBase and Zookeeper at TamtayHadoop, HBase and Zookeeper at Tamtay
Hadoop, HBase and Zookeeper at Tamtay
Eddie Bui
 
Javascript for php developer
Javascript for php developerJavascript for php developer
Javascript for php developer
Dang Tuan
 
Speaker dang minh tuan javascript for php developer
Speaker dang minh tuan   javascript for php developerSpeaker dang minh tuan   javascript for php developer
Speaker dang minh tuan javascript for php developer
AiTi Education
 
Python moi
Python moiPython moi
Python moi
DÉp LÊ
 
The Art of Readable Code - DongPV
The Art of Readable Code - DongPVThe Art of Readable Code - DongPV
The Art of Readable Code - DongPV
Đông Đô
 
Bài giảng ngôn ngữ lập trình hiện nay: Ngôn ngữ Python
Bài giảng ngôn ngữ lập trình hiện nay: Ngôn ngữ PythonBài giảng ngôn ngữ lập trình hiện nay: Ngôn ngữ Python
Bài giảng ngôn ngữ lập trình hiện nay: Ngôn ngữ Python
dtmanh1
 
Bài giảng ngôn ngữ lập trình hiện nay: Python
Bài giảng ngôn ngữ lập trình hiện nay: PythonBài giảng ngôn ngữ lập trình hiện nay: Python
Bài giảng ngôn ngữ lập trình hiện nay: Python
dtmanh1
 
Technical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vnTechnical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vn
Asahina Infotech
 

Recently uploaded (20)

20 ĐỀ ÔN THI TUYỂN SINH VÀO LỚP 10 THPT NĂM HỌC 2025-2026 MÔN TIẾNG ANH - HẢI...
20 ĐỀ ÔN THI TUYỂN SINH VÀO LỚP 10 THPT NĂM HỌC 2025-2026 MÔN TIẾNG ANH - HẢI...20 ĐỀ ÔN THI TUYỂN SINH VÀO LỚP 10 THPT NĂM HỌC 2025-2026 MÔN TIẾNG ANH - HẢI...
20 ĐỀ ÔN THI TUYỂN SINH VÀO LỚP 10 THPT NĂM HỌC 2025-2026 MÔN TIẾNG ANH - HẢI...
Nguyen Thanh Tu Collection
 
Chuong_4_QLPTTCHCNN.pptxsqsqsqsqsqsqsqsqs
Chuong_4_QLPTTCHCNN.pptxsqsqsqsqsqsqsqsqsChuong_4_QLPTTCHCNN.pptxsqsqsqsqsqsqsqsqs
Chuong_4_QLPTTCHCNN.pptxsqsqsqsqsqsqsqsqs
DungTran572675
 
SLIDES KỸ NĂNG BÁN HÀNG TRONG BỐI CẢNH CN SỐ
SLIDES KỸ NĂNG BÁN HÀNG TRONG BỐI CẢNH CN SỐSLIDES KỸ NĂNG BÁN HÀNG TRONG BỐI CẢNH CN SỐ
SLIDES KỸ NĂNG BÁN HÀNG TRONG BỐI CẢNH CN SỐ
phamtrang201104
 
Website Analysis.pdfWebsite Ample.pdfWebsite Ample.pdf
Website Analysis.pdfWebsite Ample.pdfWebsite Ample.pdfWebsite Analysis.pdfWebsite Ample.pdfWebsite Ample.pdf
Website Analysis.pdfWebsite Ample.pdfWebsite Ample.pdf
minhducnguyenforwork
 
'Cuộc đua' AI giữa DeepSeek, ChatGPT, Grok và những bất ngờ lớn.pptx
'Cuộc đua' AI giữa DeepSeek, ChatGPT, Grok và những bất ngờ lớn.pptx'Cuộc đua' AI giữa DeepSeek, ChatGPT, Grok và những bất ngờ lớn.pptx
'Cuộc đua' AI giữa DeepSeek, ChatGPT, Grok và những bất ngờ lớn.pptx
nguyenthanhtung68
 
Trung Quốc sử dụng... trí tuệ nhân tạo DeepSeek để thiết kế tiêm kích hiện đạ...
Trung Quốc sử dụng... trí tuệ nhân tạo DeepSeek để thiết kế tiêm kích hiện đạ...Trung Quốc sử dụng... trí tuệ nhân tạo DeepSeek để thiết kế tiêm kích hiện đạ...
Trung Quốc sử dụng... trí tuệ nhân tạo DeepSeek để thiết kế tiêm kích hiện đạ...
nguyenthanhtung68
 
Tại sao ta dễ ghen vô lý và cách nhận diện cảm xúc tiêu cực trong tình yêu
Tại sao ta dễ ghen vô lý và cách nhận diện cảm xúc tiêu cực trong tình yêuTại sao ta dễ ghen vô lý và cách nhận diện cảm xúc tiêu cực trong tình yêu
Tại sao ta dễ ghen vô lý và cách nhận diện cảm xúc tiêu cực trong tình yêu
Huỳnh Cảnh Nhi
 
CHUONG 3 - Cam bien VI TRI KHOANG CACH.pdf
CHUONG 3 - Cam bien VI TRI KHOANG CACH.pdfCHUONG 3 - Cam bien VI TRI KHOANG CACH.pdf
CHUONG 3 - Cam bien VI TRI KHOANG CACH.pdf
toantrung14
 
Công cụ tư duy trong dạy học Lịch sử THPT
Công cụ tư duy trong dạy học Lịch sử THPTCông cụ tư duy trong dạy học Lịch sử THPT
Công cụ tư duy trong dạy học Lịch sử THPT
ssuserf4e15d
 
2.Cô MỸ TRANG-Chuyen de - Lap ke hoach DH (gui HV) (1).pdf
2.Cô MỸ TRANG-Chuyen de - Lap ke hoach DH (gui HV) (1).pdf2.Cô MỸ TRANG-Chuyen de - Lap ke hoach DH (gui HV) (1).pdf
2.Cô MỸ TRANG-Chuyen de - Lap ke hoach DH (gui HV) (1).pdf
vodanhpl01
 
báo cáo chương lý thuyết trong powerbi.docx
báo cáo chương lý thuyết trong powerbi.docxbáo cáo chương lý thuyết trong powerbi.docx
báo cáo chương lý thuyết trong powerbi.docx
teddy04092006
 
ĐO LƯỜNG CẢM XÚC HOÀI NIỆM CỦA KHÁCH DU LỊCH TẠI ĐIỂM ĐẾN THÀNH PHỐ HUẾ.pdf
ĐO LƯỜNG CẢM XÚC HOÀI NIỆM CỦA KHÁCH DU LỊCH TẠI ĐIỂM ĐẾN THÀNH PHỐ HUẾ.pdfĐO LƯỜNG CẢM XÚC HOÀI NIỆM CỦA KHÁCH DU LỊCH TẠI ĐIỂM ĐẾN THÀNH PHỐ HUẾ.pdf
ĐO LƯỜNG CẢM XÚC HOÀI NIỆM CỦA KHÁCH DU LỊCH TẠI ĐIỂM ĐẾN THÀNH PHỐ HUẾ.pdf
TunH228308
 
VẤN ĐỀ DÂN TỘC TRONG THỜI KỲ QUÁ ĐỘ LÊN CHỦ NGHĨA XÃ HỘI.pptx
VẤN ĐỀ DÂN TỘC TRONG THỜI KỲ QUÁ ĐỘ LÊN CHỦ NGHĨA XÃ HỘI.pptxVẤN ĐỀ DÂN TỘC TRONG THỜI KỲ QUÁ ĐỘ LÊN CHỦ NGHĨA XÃ HỘI.pptx
VẤN ĐỀ DÂN TỘC TRONG THỜI KỲ QUÁ ĐỘ LÊN CHỦ NGHĨA XÃ HỘI.pptx
ngocmowx2205
 
Tai lieu Test he thong LMS Hifly - Module 1
Tai lieu Test he thong LMS Hifly - Module 1Tai lieu Test he thong LMS Hifly - Module 1
Tai lieu Test he thong LMS Hifly - Module 1
nguyenngocthanhphong1
 
Chuong 2 ktdSDGGWGWDGFaFGASRGADHDHAYR.pdf
Chuong 2 ktdSDGGWGWDGFaFGASRGADHDHAYR.pdfChuong 2 ktdSDGGWGWDGFaFGASRGADHDHAYR.pdf
Chuong 2 ktdSDGGWGWDGFaFGASRGADHDHAYR.pdf
khoanguyen20042004
 
This is a presentation about HIERARCHYCAL CLUSTERING
This is a presentation about HIERARCHYCAL CLUSTERINGThis is a presentation about HIERARCHYCAL CLUSTERING
This is a presentation about HIERARCHYCAL CLUSTERING
TonNguynThi
 
Bài 11 Tổng hợp và phân giải các chất trong tế bào.pptx
Bài 11 Tổng hợp và phân giải các chất trong tế bào.pptxBài 11 Tổng hợp và phân giải các chất trong tế bào.pptx
Bài 11 Tổng hợp và phân giải các chất trong tế bào.pptx
nguyenminhthutyt
 
"Lý thuyết học tập xã hội" - LTCTXH.pptx
"Lý thuyết học tập xã hội" - LTCTXH.pptx"Lý thuyết học tập xã hội" - LTCTXH.pptx
"Lý thuyết học tập xã hội" - LTCTXH.pptx
ThVng18
 
file Pre sen ta tion 1 vat lieu moi.pptx
file Pre sen ta tion 1 vat lieu moi.pptxfile Pre sen ta tion 1 vat lieu moi.pptx
file Pre sen ta tion 1 vat lieu moi.pptx
MinhKhoaVang
 
Ứng dụng của cách mạng công nghiệp 4.0 .pptx
Ứng dụng của cách mạng công nghiệp 4.0 .pptxỨng dụng của cách mạng công nghiệp 4.0 .pptx
Ứng dụng của cách mạng công nghiệp 4.0 .pptx
ngNam82
 
20 ĐỀ ÔN THI TUYỂN SINH VÀO LỚP 10 THPT NĂM HỌC 2025-2026 MÔN TIẾNG ANH - HẢI...
20 ĐỀ ÔN THI TUYỂN SINH VÀO LỚP 10 THPT NĂM HỌC 2025-2026 MÔN TIẾNG ANH - HẢI...20 ĐỀ ÔN THI TUYỂN SINH VÀO LỚP 10 THPT NĂM HỌC 2025-2026 MÔN TIẾNG ANH - HẢI...
20 ĐỀ ÔN THI TUYỂN SINH VÀO LỚP 10 THPT NĂM HỌC 2025-2026 MÔN TIẾNG ANH - HẢI...
Nguyen Thanh Tu Collection
 
Chuong_4_QLPTTCHCNN.pptxsqsqsqsqsqsqsqsqs
Chuong_4_QLPTTCHCNN.pptxsqsqsqsqsqsqsqsqsChuong_4_QLPTTCHCNN.pptxsqsqsqsqsqsqsqsqs
Chuong_4_QLPTTCHCNN.pptxsqsqsqsqsqsqsqsqs
DungTran572675
 
SLIDES KỸ NĂNG BÁN HÀNG TRONG BỐI CẢNH CN SỐ
SLIDES KỸ NĂNG BÁN HÀNG TRONG BỐI CẢNH CN SỐSLIDES KỸ NĂNG BÁN HÀNG TRONG BỐI CẢNH CN SỐ
SLIDES KỸ NĂNG BÁN HÀNG TRONG BỐI CẢNH CN SỐ
phamtrang201104
 
Website Analysis.pdfWebsite Ample.pdfWebsite Ample.pdf
Website Analysis.pdfWebsite Ample.pdfWebsite Ample.pdfWebsite Analysis.pdfWebsite Ample.pdfWebsite Ample.pdf
Website Analysis.pdfWebsite Ample.pdfWebsite Ample.pdf
minhducnguyenforwork
 
'Cuộc đua' AI giữa DeepSeek, ChatGPT, Grok và những bất ngờ lớn.pptx
'Cuộc đua' AI giữa DeepSeek, ChatGPT, Grok và những bất ngờ lớn.pptx'Cuộc đua' AI giữa DeepSeek, ChatGPT, Grok và những bất ngờ lớn.pptx
'Cuộc đua' AI giữa DeepSeek, ChatGPT, Grok và những bất ngờ lớn.pptx
nguyenthanhtung68
 
Trung Quốc sử dụng... trí tuệ nhân tạo DeepSeek để thiết kế tiêm kích hiện đạ...
Trung Quốc sử dụng... trí tuệ nhân tạo DeepSeek để thiết kế tiêm kích hiện đạ...Trung Quốc sử dụng... trí tuệ nhân tạo DeepSeek để thiết kế tiêm kích hiện đạ...
Trung Quốc sử dụng... trí tuệ nhân tạo DeepSeek để thiết kế tiêm kích hiện đạ...
nguyenthanhtung68
 
Tại sao ta dễ ghen vô lý và cách nhận diện cảm xúc tiêu cực trong tình yêu
Tại sao ta dễ ghen vô lý và cách nhận diện cảm xúc tiêu cực trong tình yêuTại sao ta dễ ghen vô lý và cách nhận diện cảm xúc tiêu cực trong tình yêu
Tại sao ta dễ ghen vô lý và cách nhận diện cảm xúc tiêu cực trong tình yêu
Huỳnh Cảnh Nhi
 
CHUONG 3 - Cam bien VI TRI KHOANG CACH.pdf
CHUONG 3 - Cam bien VI TRI KHOANG CACH.pdfCHUONG 3 - Cam bien VI TRI KHOANG CACH.pdf
CHUONG 3 - Cam bien VI TRI KHOANG CACH.pdf
toantrung14
 
Công cụ tư duy trong dạy học Lịch sử THPT
Công cụ tư duy trong dạy học Lịch sử THPTCông cụ tư duy trong dạy học Lịch sử THPT
Công cụ tư duy trong dạy học Lịch sử THPT
ssuserf4e15d
 
2.Cô MỸ TRANG-Chuyen de - Lap ke hoach DH (gui HV) (1).pdf
2.Cô MỸ TRANG-Chuyen de - Lap ke hoach DH (gui HV) (1).pdf2.Cô MỸ TRANG-Chuyen de - Lap ke hoach DH (gui HV) (1).pdf
2.Cô MỸ TRANG-Chuyen de - Lap ke hoach DH (gui HV) (1).pdf
vodanhpl01
 
báo cáo chương lý thuyết trong powerbi.docx
báo cáo chương lý thuyết trong powerbi.docxbáo cáo chương lý thuyết trong powerbi.docx
báo cáo chương lý thuyết trong powerbi.docx
teddy04092006
 
ĐO LƯỜNG CẢM XÚC HOÀI NIỆM CỦA KHÁCH DU LỊCH TẠI ĐIỂM ĐẾN THÀNH PHỐ HUẾ.pdf
ĐO LƯỜNG CẢM XÚC HOÀI NIỆM CỦA KHÁCH DU LỊCH TẠI ĐIỂM ĐẾN THÀNH PHỐ HUẾ.pdfĐO LƯỜNG CẢM XÚC HOÀI NIỆM CỦA KHÁCH DU LỊCH TẠI ĐIỂM ĐẾN THÀNH PHỐ HUẾ.pdf
ĐO LƯỜNG CẢM XÚC HOÀI NIỆM CỦA KHÁCH DU LỊCH TẠI ĐIỂM ĐẾN THÀNH PHỐ HUẾ.pdf
TunH228308
 
VẤN ĐỀ DÂN TỘC TRONG THỜI KỲ QUÁ ĐỘ LÊN CHỦ NGHĨA XÃ HỘI.pptx
VẤN ĐỀ DÂN TỘC TRONG THỜI KỲ QUÁ ĐỘ LÊN CHỦ NGHĨA XÃ HỘI.pptxVẤN ĐỀ DÂN TỘC TRONG THỜI KỲ QUÁ ĐỘ LÊN CHỦ NGHĨA XÃ HỘI.pptx
VẤN ĐỀ DÂN TỘC TRONG THỜI KỲ QUÁ ĐỘ LÊN CHỦ NGHĨA XÃ HỘI.pptx
ngocmowx2205
 
Tai lieu Test he thong LMS Hifly - Module 1
Tai lieu Test he thong LMS Hifly - Module 1Tai lieu Test he thong LMS Hifly - Module 1
Tai lieu Test he thong LMS Hifly - Module 1
nguyenngocthanhphong1
 
Chuong 2 ktdSDGGWGWDGFaFGASRGADHDHAYR.pdf
Chuong 2 ktdSDGGWGWDGFaFGASRGADHDHAYR.pdfChuong 2 ktdSDGGWGWDGFaFGASRGADHDHAYR.pdf
Chuong 2 ktdSDGGWGWDGFaFGASRGADHDHAYR.pdf
khoanguyen20042004
 
This is a presentation about HIERARCHYCAL CLUSTERING
This is a presentation about HIERARCHYCAL CLUSTERINGThis is a presentation about HIERARCHYCAL CLUSTERING
This is a presentation about HIERARCHYCAL CLUSTERING
TonNguynThi
 
Bài 11 Tổng hợp và phân giải các chất trong tế bào.pptx
Bài 11 Tổng hợp và phân giải các chất trong tế bào.pptxBài 11 Tổng hợp và phân giải các chất trong tế bào.pptx
Bài 11 Tổng hợp và phân giải các chất trong tế bào.pptx
nguyenminhthutyt
 
"Lý thuyết học tập xã hội" - LTCTXH.pptx
"Lý thuyết học tập xã hội" - LTCTXH.pptx"Lý thuyết học tập xã hội" - LTCTXH.pptx
"Lý thuyết học tập xã hội" - LTCTXH.pptx
ThVng18
 
file Pre sen ta tion 1 vat lieu moi.pptx
file Pre sen ta tion 1 vat lieu moi.pptxfile Pre sen ta tion 1 vat lieu moi.pptx
file Pre sen ta tion 1 vat lieu moi.pptx
MinhKhoaVang
 
Ứng dụng của cách mạng công nghiệp 4.0 .pptx
Ứng dụng của cách mạng công nghiệp 4.0 .pptxỨng dụng của cách mạng công nghiệp 4.0 .pptx
Ứng dụng của cách mạng công nghiệp 4.0 .pptx
ngNam82
 
Ad

Golang web database3

  • 2. Database ● Go doesn't provide any database drivers, but it does have a driver interface defined in the database/sql package – The advantage is that if your code is developed according to these interface standards, you will not need to change any code if your database changes. ● We always see the following code when we use third-party drivers: – Import ( "database/sql" _ "github.com/mattn/go-sqlite3" ) – Here the underscore (also known as a 'blank') “_”: ● “_” được dùng trong các hàm (func) lúc trả về các giá trị mà chúng ta không cần thì chúng ta sẽ loại bỏ nó (discarding) Khi bạn import một thư viện thì bạn sẽ phải dùng tất cả các package đó (nếu không dùng package đó trong đoạn code nào đó thì Go sẽ biên dịch và cảnh báo lại). → khi sử dụng underscore “_” khi import thư viện thì có nghĩa là bạn chỉ cần dùng function init() mà không cần sử dụng trực tiếp → tính năng này cần thiết cho registering database drivers vì nó sẽ tự động đăng ký database drivers mà không cần phải gọi nó
  • 3. Database ● Function: – sql.Register(): registering database drivers when you use third-party database drivers. ● Gọi hàm này trong hàm init() – driver.Driver: is an interface containing an Open(name string) method that returns a Conn interface. – driver.Conn: This is a database connection interface with some methods the same Conn can only be used in one goroutine. – driver.Stmt – driver.Tx
  • 4. Database ● Quy trình: – Step 0: Importing a Database Driver ● L y package:ấ – go get github.com/go-sql-driver/mysql ● Import trong mã ngu nồ import ( "database/sql" _ "github.com/go-sql-driver/mysql" )
  • 5. Database ● Quy trình: – Step 1: s d ngử ụ sql.Open đ chu n b k t n iể ẩ ị ế ố ● db, err := sql.Open(<driver name>, <command_to_connect>) – <command_to_connect>: driver-specific syntax that tells the driver how to access the underlying datastore – Giá tr tr v : c n ki m traị ả ề ầ ể handle errors ● Ví d :ụ – db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/hello") – db, err := sql.Open("mysql", "<user>:<password>@/test?charset=utf8") ● Sql.Open ch a t o k t n i ngayư ạ ế ố – Nó t o k t n i ch khi nào có yêu c u (query) đ u tiên.ạ ế ố ỉ ầ ầ – db.Ping() dùng đ ki m tra database is available and accessible (forể ể example, check that you can establish a network connection and log in)
  • 6. Database ● Quy trình: – Step 2: T o m i d li u, g m 3 b c:ạ ớ ữ ệ ồ ướ ● stmt, err := db.Prepare(<command>): chu n b đ nh d ng d li u đ chèn vào DBẩ ị ị ạ ữ ệ ể – returns a SQL operation that is going to be executed. It also returns the execution status after executing SQL. – db là giá tr tr v t hàm slq.Open()ị ả ề ừ – Ví d : db.Prepare("INSERT userinfo SETụ username=?,departname=?,created=?") ● res, err := stmt.Exec(<data>): th c hi n l nhự ệ ệ – Stmt là giá tr tr v t hàm db.Prepare()ị ả ề ừ – <data>: là m u chu n theo th t đã xác đ nh trên b c chu n b trênẫ ẩ ứ ự ị ướ ẩ ị – Ví d : stmt.Exec("astaxie", "a72", "2016-12-09") → tuân theo chu n <username,departname,created> trênụ ẩ ở ● res.<Action>: đ c giá tr tr v sau khi th c hi n l nhọ ị ả ề ự ệ ệ – res là giá tr tr v t hàmị ả ề ừ stmt.Exec() – Có các Action khác nhau: ● id, err := res.LastInsertId() ● affect, err := res.RowsAffected()
  • 7. Database ● Quy trình: – Step 3: Truy v n tìm ki m d li uấ ế ữ ệ ● L nh truy v n:ệ ấ db.Query(<command_to_query>) – rows, err := db.Query("SELECT * FROM userinfo") ● Duy t danh sách tr v :ệ ả ề – rows.Next(): – rows.Scan(): read the columns in each row into variables ● defer rows.Close(): đóng rows for rows.Next() { → l y l n l t các row tr vấ ầ ượ ả ề err = rows.Scan(&uid, &username, &department, &created) }
  • 8. Database ● Quy trình: – Step 4: Xóa d li u (t ng t nh Step2)ữ ệ ươ ự ư ● stmt, err = db.Prepare(<command_to_del>) – <command_to_del>: là l nh mysql đ xóa d li uệ ể ữ ệ – stmt, err = db.Prepare("delete from userinfo where uid=?") ● res, err = stmt.Exec(id) – Stmt thi u giá tr d li uế ị ữ ệ id nên l nh này đ a id vào và th c thiệ ư ự l nh xóaệ ● affect, err = res.RowsAffected() Note that we use the format =? to pass arguments. This is necessary for preventing SQL injection attacks.
  • 9. Database ● Ví d đ c DB Mysql:ụ ọ – K t n i:ế ố ● db, err := sql.Open("mysql", "astaxie:astaxie@/test?charset=utf8") ● db.Close() – Ghi d li u:ữ ệ ● stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?") ● res, err := stmt.Exec("jace", "jace in corp", "2015-12-09") ● id, err := res.LastInsertId() → ki m ch ng l n ghi d li u v a r iể ứ ầ ữ ệ ừ ồ – C p nh p/S a d li uậ ậ ử ữ ệ ● stmt, err = db.Prepare("update userinfo set username=? where uid=?") ● res, err = stmt.Exec("astaxieupdate", id) ● affect, err := res.RowsAffected() → ki m ch ng l nh update có đúng đ i t ng (rows)ể ứ ệ ố ượ – Tìm ki m d li u:ế ữ ệ ● rows, err := db.Query("SELECT * FROM userinfo") ● for rows.Next() {err = rows.Scan(&uid, &username, &department, &created)} – Xóa d li u:ữ ệ ● stmt, err = db.Prepare("delete from userinfo where uid=?") ● res, err = stmt.Exec(id) → th c thi l nh xóaự ệ ● affect, err = res.RowsAffected() → ki m ch ng l nh xóa có đúng đ i t ng khôngể ứ ệ ố ượ
  • 10. Database ● Làm vi c v i Redisệ ớ – redis is a key-value storage system like Memcached, that supports the string, list, set and zset(ordered set) value types. – Download: http://redis.io/download – Cài đ t và th nghi m:ặ ử ệ ● Ch y server: src/redis-serverạ ● T ng tác, thao tác d li u v i server: src/redis-cliươ ữ ệ ớ – set foo bar – get foo – L y th vi n database driver:ấ ư ệ ● go get github.com/astaxie/goredis
  • 11. Database ● Làm vi c v i Redisệ ớ – Các th vi n giao ti p v i redis:ư ệ ế ớ ● https://github.com/fzzy/radix ● https://github.com/alphazero/Go-Redis – Current status is compatible with Redis 2.4.n (2.4.9 tested) and Go 1 – đã lâu không có b n c p nh tả ậ ậ ● https://github.com/simonz05/godis → b n c p nh t đã khá cũ (2012)ả ậ ậ ● https://github.com/hoisie/redis → Designed for Redis 2.6.x. ● https://github.com/garyburd/redigo – B n m i nh t vào Tháng 5/2016ả ớ ấ –
  • 12. Database ● Làm vi c v i Redis:ệ ớ – M t s ví d t ng tác v i Redis:ộ ố ụ ươ ớ ● https://github.com/ovr/go-redis ● https://github.com/wen866595/gredis ● https://github.com/hongruiqi/redis.go ●
  • 13. cookies ● Cookies g m các tr ng:ồ ườ – Name: string – Value: string – Path: string – Domain: string – Expires: time.Time – RawExpires: string – MaxAge: int – Secure: bool – HttpOnly: bool – Raw: string – Unparsed: []string ● Go uses the SetCookie function in the net/http package to set cookies: – http.SetCookie(w ResponseWriter, cookie *Cookie) – Hàm này có th dùng cho c 2 tr ng h p t o cookies và xóa cookies.ể ả ườ ợ ạ
  • 14. cookies func login(w http.ResponseWriter, r *http.Request) { SetCookie(w) } login là 1 Handler c a web.ủ Hàm Setcookie s d ng ReponseWriter đ tr v cho clientử ụ ể ả ề func sayhelloName(w http.ResponseWriter, r *http.Request) { GetCookie(r) } sayhelloName là 1 Handler c a webủ Hàm Getcookie s d ng Request do nh n các thông s t clientử ụ ậ ố ừ
  • 15. cookies func SetCookie(res http.ResponseWriter) { expiration := time.Now().Add(365 * 24 * time.Hour) cookie := http.Cookie{ Name: "my-cookie", Value: "COOKIE MONSTER", Expires: expiration} http.SetCookie(res, &cookie) } func GetCookie(req *http.Request) { cookie, err := req.Cookie("my-cookie") if err == nil { fmt.Println("has cookie") fmt.Println("get cookie") fmt.Println(cookie) fmt.Println(cookie.Value) fmt.Println(cookie.Expires) } else{ fmt.Println("please set cookie") fmt.Println(err) } } func ClearCookie(res http.ResponseWriter) { cookie := http.Cookie{ Name: "my-cookie", Value: "COOKIE MONSTER", MaxAge: -1} http.SetCookie(res, &cookie) }
  • 16. Session ● https://github.com/MorpheusXAUT/eveauth – Có các th vi n c n thi t v thao tác sessionư ệ ầ ế ề ● https://github.com/icza/session – Th vi n v i các ch ng năng qu n lý session kháư ệ ớ ứ ả h u d ngữ ụ
  • 17. Network service ● we need an IP address and port number to have a unique socket. ● TCP socket – TCPConn struct đ mô t 1 k t n i socket.ể ả ế ố ● TCPConn can be used by either client or server for reading and writing data. – after a connection is established, the server has the same type of connection object for the current connection → c phía client và server cùng có 1 object đ mô t k t n i.ả ể ả ế ố – clients send requests to servers through a TCPConn and receive information from the server response – servers read and parse client requests, then return feedback ● two key functions: – func (c *TCPConn) Write(b []byte) (n int, err os.Error) – func (c *TCPConn) Read(b []byte) (n int, err os.Error) – TCPAddr struct to represent TCP address information: ● ResolveTCPAddr function to get a TCPAddr
  • 18. Network service ● T o k t n i TCP:ạ ế ố – DialTCP function in the net package to create a TCP connection ● returns a TCPConn object ● func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err os.Error) –
  • 19. Tham kh oả ● https://github.com/suyesh/go_training ●

Editor's Notes

  • #5: import ( &amp;quot;database/sql&amp;quot; _ &amp;quot;github.com/go-sql-driver/mysql&amp;quot; )
  • #7: import ( &amp;quot;database/sql&amp;quot; _ &amp;quot;github.com/go-sql-driver/mysql&amp;quot; )
  • #8: import ( &amp;quot;database/sql&amp;quot; _ &amp;quot;github.com/go-sql-driver/mysql&amp;quot; )
  • #9: import ( &amp;quot;database/sql&amp;quot; _ &amp;quot;github.com/go-sql-driver/mysql&amp;quot; )
  • #15: Mỗi 1 webserver chỉ có 1 loại handler nên các hàm lấy và tạo cookie thường đưa vào Package hoặc Func để gọi từ bên trong các Handler, phục vụ việc kiểm tra điều kiện cho các Handler