-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathr-rysql-crud.r
94 lines (76 loc) · 2.94 KB
/
r-rysql-crud.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
install.packages(c("DBI", "RMySQL"))
library(DBI)
library(RMySQL)
# Define the Database class
Database <- setRefClass("Database",
fields = list(
host = "character",
user = "character",
password = "character",
database = "character",
connection = "ANY"
),
methods = list(
initialize = function(host="localhost", user="user", password="password", database="database") {
.self$host <- host
.self$user <- user
.self$password <- password
.self$database <- database
.self$connect()
},
connect = function() {
.self$connection <- dbConnect(RMySQL::MySQL(), host = .self$host, user = .self$user, password = .self$password, dbname = .self$database)
},
disconnect = function() {
dbDisconnect(.self$connection)
},
query = function(sql) {
result <- dbSendQuery(.self$connection, sql)
return(result)
},
select = function(table, rows="*", where=NULL, order=NULL, limit=NULL) {
sql <- paste0("SELECT ", rows, " FROM ", table)
if (!is.null(where)) sql <- paste0(sql, " WHERE ", where)
if (!is.null(order)) sql <- paste0(sql, " ORDER BY ", order)
if (!is.null(limit)) sql <- paste0(sql, " LIMIT ", limit)
return(.self$query(sql))
},
insert = function(table, values, columns=NULL) {
col_string <- if (!is.null(columns)) paste0("(", paste(columns, collapse=", "), ")") else ""
val_string <- paste0("('", paste(values, collapse="', '"), "')")
sql <- paste0("INSERT INTO ", table, " ", col_string, " VALUES ", val_string)
return(.self$query(sql))
},
update = function(table, set, where=NULL) {
sql <- paste0("UPDATE ", table, " SET ", set)
if (!is.null(where)) sql <- paste0(sql, " WHERE ", where)
return(.self$query(sql))
},
delete = function(table, where) {
sql <- paste0("DELETE FROM ", table, " WHERE ", where)
return(.self$query(sql))
}
)
)
# Create Database instance
db <- Database$new()
# Use the Database instance for operations
tryCatch({
# Insert
db$insert("users", c("john_doe", "[email protected]", "password123"), c("username", "email", "password"))
print("Insert: New user added.")
# Select
result <- db$select("users")
print("Select: List of all users:")
print(fetch(result))
# Update
db$update("users", "email='[email protected]'", "id=1")
print("Update: Email of user with ID 1 updated.")
# Delete
db$delete("users", "id=1")
print("Delete: User with ID 1 deleted.")
}, error = function(e) {
print(paste("An error occurred:", e))
})
# Disconnect
db$disconnect()