SlideShare ist ein Scribd-Unternehmen logo
1 von 19
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
●

Weitere ähnliche Inhalte

Ähnlich wie Golang web database3

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ếnSon 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ệcmanhvokiem
 
Javascript tong-hop a-z
Javascript tong-hop a-zJavascript tong-hop a-z
Javascript tong-hop a-zManhh Nguyễn
 
Qtu.vn sql - chuong 7
Qtu.vn  sql - chuong 7Qtu.vn  sql - chuong 7
Qtu.vn sql - chuong 7Hoang 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 PHPelearninglabvn
 
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 itbamboosky4991
 
Hadoop, HBase and Zookeeper at Tamtay
Hadoop, HBase and Zookeeper at TamtayHadoop, HBase and Zookeeper at Tamtay
Hadoop, HBase and Zookeeper at TamtayEddie Bui
 
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 developerAiTi Education
 
Javascript for php developer
Javascript for php developerJavascript for php developer
Javascript for php developerDang Tuan
 
Python moi
Python moiPython moi
Python moiDÉ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 Đô
 
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_vnAsahina Infotech
 
DoThanhNghi2016_Python.pdf
DoThanhNghi2016_Python.pdfDoThanhNghi2016_Python.pdf
DoThanhNghi2016_Python.pdfTamDo58
 
Storedprocedure 140411073406-phpapp02
Storedprocedure 140411073406-phpapp02Storedprocedure 140411073406-phpapp02
Storedprocedure 140411073406-phpapp02huynhtrong774129
 

Ähnlich wie Golang web database3 (20)

Php day4
Php day4Php day4
Php day4
 
Ch06
Ch06Ch06
Ch06
 
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
 
Giao trinh java script
Giao trinh java scriptGiao trinh java script
Giao trinh java script
 
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
 
Map reduce hdfs
Map reduce hdfsMap reduce hdfs
Map reduce hdfs
 
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
 
Javascript tong-hop a-z
Javascript tong-hop a-zJavascript tong-hop a-z
Javascript tong-hop a-z
 
Qtu.vn sql - chuong 7
Qtu.vn  sql - chuong 7Qtu.vn  sql - chuong 7
Qtu.vn sql - chuong 7
 
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
 
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
 
Jquery
JqueryJquery
Jquery
 
Hadoop, HBase and Zookeeper at Tamtay
Hadoop, HBase and Zookeeper at TamtayHadoop, HBase and Zookeeper at Tamtay
Hadoop, HBase and Zookeeper at Tamtay
 
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
 
Javascript for php developer
Javascript for php developerJavascript for php developer
Javascript for php developer
 
Python moi
Python moiPython moi
Python moi
 
The Art of Readable Code - DongPV
The Art of Readable Code - DongPVThe Art of Readable Code - DongPV
The Art of Readable Code - DongPV
 
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
 
DoThanhNghi2016_Python.pdf
DoThanhNghi2016_Python.pdfDoThanhNghi2016_Python.pdf
DoThanhNghi2016_Python.pdf
 
Storedprocedure 140411073406-phpapp02
Storedprocedure 140411073406-phpapp02Storedprocedure 140411073406-phpapp02
Storedprocedure 140411073406-phpapp02
 

Kürzlich hochgeladen

30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...Nguyen Thanh Tu Collection
 
Bài giảng môn Truyền thông đa phương tiện
Bài giảng môn Truyền thông đa phương tiệnBài giảng môn Truyền thông đa phương tiện
Bài giảng môn Truyền thông đa phương tiệnpmtiendhti14a5hn
 
SD-05_Xây dựng website bán váy Lolita Alice - Phùng Thị Thúy Hiền PH 2 7 8 6 ...
SD-05_Xây dựng website bán váy Lolita Alice - Phùng Thị Thúy Hiền PH 2 7 8 6 ...SD-05_Xây dựng website bán váy Lolita Alice - Phùng Thị Thúy Hiền PH 2 7 8 6 ...
SD-05_Xây dựng website bán váy Lolita Alice - Phùng Thị Thúy Hiền PH 2 7 8 6 ...ChuThNgnFEFPLHN
 
SLIDE - Tu van, huong dan cong tac tuyen sinh-2024 (đầy đủ chi tiết).pdf
SLIDE - Tu van, huong dan cong tac tuyen sinh-2024 (đầy đủ chi tiết).pdfSLIDE - Tu van, huong dan cong tac tuyen sinh-2024 (đầy đủ chi tiết).pdf
SLIDE - Tu van, huong dan cong tac tuyen sinh-2024 (đầy đủ chi tiết).pdfhoangtuansinh1
 
xemsomenh.com-Vòng Lộc Tồn - Vòng Bác Sĩ và Cách An Trong Vòng Lộc Tồn.pdf
xemsomenh.com-Vòng Lộc Tồn - Vòng Bác Sĩ và Cách An Trong Vòng Lộc Tồn.pdfxemsomenh.com-Vòng Lộc Tồn - Vòng Bác Sĩ và Cách An Trong Vòng Lộc Tồn.pdf
xemsomenh.com-Vòng Lộc Tồn - Vòng Bác Sĩ và Cách An Trong Vòng Lộc Tồn.pdfXem Số Mệnh
 
3-BẢNG MÃ LỖI CỦA CÁC HÃNG ĐIỀU HÒA .pdf - ĐIỆN LẠNH BÁCH KHOA HÀ NỘI
3-BẢNG MÃ LỖI CỦA CÁC HÃNG ĐIỀU HÒA .pdf - ĐIỆN LẠNH BÁCH KHOA HÀ NỘI3-BẢNG MÃ LỖI CỦA CÁC HÃNG ĐIỀU HÒA .pdf - ĐIỆN LẠNH BÁCH KHOA HÀ NỘI
3-BẢNG MÃ LỖI CỦA CÁC HÃNG ĐIỀU HÒA .pdf - ĐIỆN LẠNH BÁCH KHOA HÀ NỘIĐiện Lạnh Bách Khoa Hà Nội
 
Đề thi tin học HK2 lớp 3 Chân Trời Sáng Tạo
Đề thi tin học HK2 lớp 3 Chân Trời Sáng TạoĐề thi tin học HK2 lớp 3 Chân Trời Sáng Tạo
Đề thi tin học HK2 lớp 3 Chân Trời Sáng Tạowindcances
 
TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI KỸ NĂNG VIẾT ĐOẠN VĂN NGHỊ LUẬN XÃ HỘI 200 C...
TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI KỸ NĂNG VIẾT ĐOẠN VĂN NGHỊ LUẬN XÃ HỘI 200 C...TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI KỸ NĂNG VIẾT ĐOẠN VĂN NGHỊ LUẬN XÃ HỘI 200 C...
TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI KỸ NĂNG VIẾT ĐOẠN VĂN NGHỊ LUẬN XÃ HỘI 200 C...Nguyen Thanh Tu Collection
 
Giáo trình nhập môn lập trình - Đặng Bình Phương
Giáo trình nhập môn lập trình - Đặng Bình PhươngGiáo trình nhập môn lập trình - Đặng Bình Phương
Giáo trình nhập môn lập trình - Đặng Bình Phươnghazzthuan
 
Kiến thức cơ bản về tư duy số - VTC Net Viet
Kiến thức cơ bản về tư duy số - VTC Net VietKiến thức cơ bản về tư duy số - VTC Net Viet
Kiến thức cơ bản về tư duy số - VTC Net VietNguyễn Quang Huy
 
Bài tập nhóm Kỹ Năng Gỉai Quyết Tranh Chấp Lao Động (1).pptx
Bài tập nhóm Kỹ Năng Gỉai Quyết Tranh Chấp Lao Động (1).pptxBài tập nhóm Kỹ Năng Gỉai Quyết Tranh Chấp Lao Động (1).pptx
Bài tập nhóm Kỹ Năng Gỉai Quyết Tranh Chấp Lao Động (1).pptxDungxPeach
 
kinh tế chính trị mác lênin chương hai và hàng hoá và sxxhh
kinh tế chính trị mác lênin chương hai và hàng hoá và sxxhhkinh tế chính trị mác lênin chương hai và hàng hoá và sxxhh
kinh tế chính trị mác lênin chương hai và hàng hoá và sxxhhdtlnnm
 
TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI LÝ LUẬN VĂN HỌC NĂM HỌC 2023-2024 - MÔN NGỮ ...
TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI LÝ LUẬN VĂN HỌC NĂM HỌC 2023-2024 - MÔN NGỮ ...TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI LÝ LUẬN VĂN HỌC NĂM HỌC 2023-2024 - MÔN NGỮ ...
TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI LÝ LUẬN VĂN HỌC NĂM HỌC 2023-2024 - MÔN NGỮ ...Nguyen Thanh Tu Collection
 
26 Truyện Ngắn Sơn Nam (Sơn Nam) thuviensach.vn.pdf
26 Truyện Ngắn Sơn Nam (Sơn Nam) thuviensach.vn.pdf26 Truyện Ngắn Sơn Nam (Sơn Nam) thuviensach.vn.pdf
26 Truyện Ngắn Sơn Nam (Sơn Nam) thuviensach.vn.pdfltbdieu
 
xemsomenh.com-Vòng Tràng Sinh - Cách An 12 Sao Và Ý Nghĩa Từng Sao.pdf
xemsomenh.com-Vòng Tràng Sinh - Cách An 12 Sao Và Ý Nghĩa Từng Sao.pdfxemsomenh.com-Vòng Tràng Sinh - Cách An 12 Sao Và Ý Nghĩa Từng Sao.pdf
xemsomenh.com-Vòng Tràng Sinh - Cách An 12 Sao Và Ý Nghĩa Từng Sao.pdfXem Số Mệnh
 
Bài học phòng cháy chữa cháy - PCCC tại tòa nhà
Bài học phòng cháy chữa cháy - PCCC tại tòa nhàBài học phòng cháy chữa cháy - PCCC tại tòa nhà
Bài học phòng cháy chữa cháy - PCCC tại tòa nhàNguyen Thi Trang Nhung
 
bài thi bảo vệ nền tảng tư tưởng của Đảng.docx
bài thi bảo vệ nền tảng tư tưởng của Đảng.docxbài thi bảo vệ nền tảng tư tưởng của Đảng.docx
bài thi bảo vệ nền tảng tư tưởng của Đảng.docxTrnHiYn5
 
BỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdf
BỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdfBỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdf
BỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdfNguyen Thanh Tu Collection
 
bài tập lớn môn kiến trúc máy tính và hệ điều hành
bài tập lớn môn kiến trúc máy tính và hệ điều hànhbài tập lớn môn kiến trúc máy tính và hệ điều hành
bài tập lớn môn kiến trúc máy tính và hệ điều hànhdangdinhkien2k4
 
powerpoint mẫu họp phụ huynh cuối kì 2 học sinh lớp 7 bgs
powerpoint mẫu họp phụ huynh cuối kì 2 học sinh lớp 7 bgspowerpoint mẫu họp phụ huynh cuối kì 2 học sinh lớp 7 bgs
powerpoint mẫu họp phụ huynh cuối kì 2 học sinh lớp 7 bgsNmmeomeo
 

Kürzlich hochgeladen (20)

30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
30 ĐỀ PHÁT TRIỂN THEO CẤU TRÚC ĐỀ MINH HỌA BGD NGÀY 22-3-2024 KỲ THI TỐT NGHI...
 
Bài giảng môn Truyền thông đa phương tiện
Bài giảng môn Truyền thông đa phương tiệnBài giảng môn Truyền thông đa phương tiện
Bài giảng môn Truyền thông đa phương tiện
 
SD-05_Xây dựng website bán váy Lolita Alice - Phùng Thị Thúy Hiền PH 2 7 8 6 ...
SD-05_Xây dựng website bán váy Lolita Alice - Phùng Thị Thúy Hiền PH 2 7 8 6 ...SD-05_Xây dựng website bán váy Lolita Alice - Phùng Thị Thúy Hiền PH 2 7 8 6 ...
SD-05_Xây dựng website bán váy Lolita Alice - Phùng Thị Thúy Hiền PH 2 7 8 6 ...
 
SLIDE - Tu van, huong dan cong tac tuyen sinh-2024 (đầy đủ chi tiết).pdf
SLIDE - Tu van, huong dan cong tac tuyen sinh-2024 (đầy đủ chi tiết).pdfSLIDE - Tu van, huong dan cong tac tuyen sinh-2024 (đầy đủ chi tiết).pdf
SLIDE - Tu van, huong dan cong tac tuyen sinh-2024 (đầy đủ chi tiết).pdf
 
xemsomenh.com-Vòng Lộc Tồn - Vòng Bác Sĩ và Cách An Trong Vòng Lộc Tồn.pdf
xemsomenh.com-Vòng Lộc Tồn - Vòng Bác Sĩ và Cách An Trong Vòng Lộc Tồn.pdfxemsomenh.com-Vòng Lộc Tồn - Vòng Bác Sĩ và Cách An Trong Vòng Lộc Tồn.pdf
xemsomenh.com-Vòng Lộc Tồn - Vòng Bác Sĩ và Cách An Trong Vòng Lộc Tồn.pdf
 
3-BẢNG MÃ LỖI CỦA CÁC HÃNG ĐIỀU HÒA .pdf - ĐIỆN LẠNH BÁCH KHOA HÀ NỘI
3-BẢNG MÃ LỖI CỦA CÁC HÃNG ĐIỀU HÒA .pdf - ĐIỆN LẠNH BÁCH KHOA HÀ NỘI3-BẢNG MÃ LỖI CỦA CÁC HÃNG ĐIỀU HÒA .pdf - ĐIỆN LẠNH BÁCH KHOA HÀ NỘI
3-BẢNG MÃ LỖI CỦA CÁC HÃNG ĐIỀU HÒA .pdf - ĐIỆN LẠNH BÁCH KHOA HÀ NỘI
 
Đề thi tin học HK2 lớp 3 Chân Trời Sáng Tạo
Đề thi tin học HK2 lớp 3 Chân Trời Sáng TạoĐề thi tin học HK2 lớp 3 Chân Trời Sáng Tạo
Đề thi tin học HK2 lớp 3 Chân Trời Sáng Tạo
 
TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI KỸ NĂNG VIẾT ĐOẠN VĂN NGHỊ LUẬN XÃ HỘI 200 C...
TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI KỸ NĂNG VIẾT ĐOẠN VĂN NGHỊ LUẬN XÃ HỘI 200 C...TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI KỸ NĂNG VIẾT ĐOẠN VĂN NGHỊ LUẬN XÃ HỘI 200 C...
TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI KỸ NĂNG VIẾT ĐOẠN VĂN NGHỊ LUẬN XÃ HỘI 200 C...
 
Giáo trình nhập môn lập trình - Đặng Bình Phương
Giáo trình nhập môn lập trình - Đặng Bình PhươngGiáo trình nhập môn lập trình - Đặng Bình Phương
Giáo trình nhập môn lập trình - Đặng Bình Phương
 
Kiến thức cơ bản về tư duy số - VTC Net Viet
Kiến thức cơ bản về tư duy số - VTC Net VietKiến thức cơ bản về tư duy số - VTC Net Viet
Kiến thức cơ bản về tư duy số - VTC Net Viet
 
Bài tập nhóm Kỹ Năng Gỉai Quyết Tranh Chấp Lao Động (1).pptx
Bài tập nhóm Kỹ Năng Gỉai Quyết Tranh Chấp Lao Động (1).pptxBài tập nhóm Kỹ Năng Gỉai Quyết Tranh Chấp Lao Động (1).pptx
Bài tập nhóm Kỹ Năng Gỉai Quyết Tranh Chấp Lao Động (1).pptx
 
kinh tế chính trị mác lênin chương hai và hàng hoá và sxxhh
kinh tế chính trị mác lênin chương hai và hàng hoá và sxxhhkinh tế chính trị mác lênin chương hai và hàng hoá và sxxhh
kinh tế chính trị mác lênin chương hai và hàng hoá và sxxhh
 
TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI LÝ LUẬN VĂN HỌC NĂM HỌC 2023-2024 - MÔN NGỮ ...
TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI LÝ LUẬN VĂN HỌC NĂM HỌC 2023-2024 - MÔN NGỮ ...TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI LÝ LUẬN VĂN HỌC NĂM HỌC 2023-2024 - MÔN NGỮ ...
TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI LÝ LUẬN VĂN HỌC NĂM HỌC 2023-2024 - MÔN NGỮ ...
 
26 Truyện Ngắn Sơn Nam (Sơn Nam) thuviensach.vn.pdf
26 Truyện Ngắn Sơn Nam (Sơn Nam) thuviensach.vn.pdf26 Truyện Ngắn Sơn Nam (Sơn Nam) thuviensach.vn.pdf
26 Truyện Ngắn Sơn Nam (Sơn Nam) thuviensach.vn.pdf
 
xemsomenh.com-Vòng Tràng Sinh - Cách An 12 Sao Và Ý Nghĩa Từng Sao.pdf
xemsomenh.com-Vòng Tràng Sinh - Cách An 12 Sao Và Ý Nghĩa Từng Sao.pdfxemsomenh.com-Vòng Tràng Sinh - Cách An 12 Sao Và Ý Nghĩa Từng Sao.pdf
xemsomenh.com-Vòng Tràng Sinh - Cách An 12 Sao Và Ý Nghĩa Từng Sao.pdf
 
Bài học phòng cháy chữa cháy - PCCC tại tòa nhà
Bài học phòng cháy chữa cháy - PCCC tại tòa nhàBài học phòng cháy chữa cháy - PCCC tại tòa nhà
Bài học phòng cháy chữa cháy - PCCC tại tòa nhà
 
bài thi bảo vệ nền tảng tư tưởng của Đảng.docx
bài thi bảo vệ nền tảng tư tưởng của Đảng.docxbài thi bảo vệ nền tảng tư tưởng của Đảng.docx
bài thi bảo vệ nền tảng tư tưởng của Đảng.docx
 
BỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdf
BỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdfBỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdf
BỘ LUYỆN NGHE VÀO 10 TIẾNG ANH DẠNG TRẮC NGHIỆM 4 CÂU TRẢ LỜI - CÓ FILE NGHE.pdf
 
bài tập lớn môn kiến trúc máy tính và hệ điều hành
bài tập lớn môn kiến trúc máy tính và hệ điều hànhbài tập lớn môn kiến trúc máy tính và hệ điều hành
bài tập lớn môn kiến trúc máy tính và hệ điều hành
 
powerpoint mẫu họp phụ huynh cuối kì 2 học sinh lớp 7 bgs
powerpoint mẫu họp phụ huynh cuối kì 2 học sinh lớp 7 bgspowerpoint mẫu họp phụ huynh cuối kì 2 học sinh lớp 7 bgs
powerpoint mẫu họp phụ huynh cuối kì 2 học sinh lớp 7 bgs
 

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 ●

Hinweis der Redaktion

  1. import ( &amp;quot;database/sql&amp;quot; _ &amp;quot;github.com/go-sql-driver/mysql&amp;quot; )
  2. import ( &amp;quot;database/sql&amp;quot; _ &amp;quot;github.com/go-sql-driver/mysql&amp;quot; )
  3. import ( &amp;quot;database/sql&amp;quot; _ &amp;quot;github.com/go-sql-driver/mysql&amp;quot; )
  4. import ( &amp;quot;database/sql&amp;quot; _ &amp;quot;github.com/go-sql-driver/mysql&amp;quot; )
  5. 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