File size: 1,315 Bytes
0480ef8
 
 
 
91944c8
0480ef8
 
 
 
359a85c
0480ef8
91944c8
0480ef8
 
 
 
 
 
 
 
 
91944c8
0480ef8
 
 
 
91944c8
 
0480ef8
 
 
91944c8
0480ef8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
library(DBI)
library(RPostgres)
library(readr) # To read your .sql file


sys_con <- dbConnect(RPostgres::Postgres(), 
                     dbname = "postgres", # Default system DB
                     host = "localhost", 
                     user = "postgres", 
                     password = "your_password_here") # 


tryCatch({
  dbExecute(sys_con, "CREATE DATABASE sales_db;")
  print("Database 'sales_db' created successfully.")
}, error = function(e) {
  print("Database 'sales_db' already exists or could not be created.")
})

dbDisconnect(sys_con) # Disconnect from system DB


con <- dbConnect(RPostgres::Postgres(), 
                 dbname = "sales_db", 
                 host = "localhost", 
                 user = "postgres", 
                 password = "ggdata2014") # 


sql_commands <- read_file("database.sql")


statements <- unlist(strsplit(sql_commands, ";"))

# Execute each statement
for (stmt in statements) {
  # clean up whitespace
  stmt_clean <- trimws(stmt)
  if (nchar(stmt_clean) > 0) {
    tryCatch({
      dbExecute(con, stmt_clean)
      print(paste("Executed:", substr(stmt_clean, 1, 50), "..."))
    }, error = function(e) {
      print(paste("Error executing:", substr(stmt_clean, 1, 50)))
      print(e)
    })
  }
}

print("Tables created successfully!")
dbDisconnect(con)