我有一个 .sql 文件,我正在尝试使用 R 包 RSQLite 将其读入 SQL 数据库。为了熟悉自己,首先,我查看了 R 数据集 mtcars:
mydb <- dbConnect(RSQLite::SQLite(), "")
dbWriteTable(mydb, "mtcars", mtcars)
str(mydb)
结构如下:
Formal class 'SQLiteConnection' [package "RSQLite"] with 5 slots
..@ Id :<externalptr>
..@ dbname : chr ""
..@ loadable.extensions: logi TRUE
..@ flags : int 6
..@ vfs : chr ""
接下来,我只是从数据库中读取了五行:
dbGetQuery(mydb, 'SELECT * FROM mtcars LIMIT 5')
row_names mpg cyl disp hp drat wt qsec vs am gear carb
1 Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
2 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
3 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
4 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
5 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
现在,我可以看到列名,也许我只对 hp>200 感兴趣,所以我这样做:
dbGetQuery(mydb, 'SELECT * FROM mtcars WHERE hp > 200')
row_names mpg cyl disp hp drat wt qsec vs am gear carb
1 Duster 360 14.3 8 360 245 3.21 3.570 15.84 0 0 3 4
2 Cadillac Fleetwood 10.4 8 472 205 2.93 5.250 17.98 0 0 3 4
3 Lincoln Continental 10.4 8 460 215 3.00 5.424 17.82 0 0 3 4
4 Chrysler Imperial 14.7 8 440 230 3.23 5.345 17.42 0 0 3 4
5 Camaro Z28 13.3 8 350 245 3.73 3.840 15.41 0 0 3 4
6 Ford Pantera L 15.8 8 351 264 4.22 3.170 14.50 0 1 5 4
7 Maserati Bora 15.0 8 301 335 3.54 3.570 14.60 0 1 5 8
现在,我实际上正在尝试查看我感兴趣的数据(不再是 mtcars),称为 myData.sql。有人告诉我这个文件是通用 SQL,我可以加载到我喜欢的任何数据库中,并且它来自 PostgreSQL。
所以,我试试这个,它输出与以前相同的结构:
mydb <- dbConnect(RSQLite::SQLite(), "myData.sql")
str(mydb)
Formal class 'SQLiteConnection' [package "RSQLite"] with 5 slots
..@ Id :<externalptr>
..@ dbname : chr "myData.sql"
..@ loadable.extensions: logi TRUE
..@ flags : int 6
..@ vfs : chr ""
现在,我想看看 myData.sql 中存储了什么,希望看到一个带有列的数据表(比如 mtcars)。但是,当我尝试时出现错误:
dbGetQuery(mydb, 'SELECT * LIMIT 5')
Error in sqliteSendQuery(con, statement, bind.data) :
error in statement: no tables specified
和
dbGetQuery(mydb, 'SELECT * FROM mydb LIMIT 5')
Error in sqliteSendQuery(con, statement, bind.data) :
error in statement: no such table: mydb
我非常不确定如何开始探索 myData.sql 中的信息。任何意见是极大的赞赏!