- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
RMySQL
和sqldf
等软件包允许与本地或远程数据库服务器进行交互。我正在创建一个可移植项目,该项目涉及在并不总是能够访问正在运行的服务器但确实总是能够访问最新的 .sql 转储的情况下(或在设备上)导入 sql 数据数据库。
目标似乎很简单:在不涉及 MySQL 服务器的情况下将 .sql 转储导入 R。更具体地说,我想创建一个列表列表,其中的元素对应于.sql 转储中定义的任何数据库(可能有多个),这些元素又由这些数据库中的表组成。
为了使其可重现,让我们使用示例 sportsdb SQL 文件 here — 如果你解压它,它叫做 sportsdb_sample_mysql_20080303.sql。
有人会认为 sqldf 可能能够做到这一点:
read.csv.sql('sportsdb_sample_mysql_20080303.sql', sql="SELECT * FROM addresses")
sqliteSendQuery(con, statement, bind.data) 错误:
语句错误:没有这样的表:地址
即使在转储中肯定有一个表地址。 This post on the sqldf list提到同样的错误,但没有解决办法。
然后ProjectTemplate
包中有一个sql.reader
函数,看起来很有前途。四处寻找,可以找到该函数的源代码 here ,它假设有一个正在运行的数据库服务器并依赖于 RMySQL
——这不是我需要的。
所以...我们似乎已经没有选择了。来自 hivemind 的任何帮助表示赞赏!
(重申一下,我不是在寻找依赖于访问 SQL 服务器的解决方案;使用 RMySQL
中的 dbReadTable
很容易> 包。我非常想绕过服务器并直接从 .sql 转储文件中获取数据。)
最佳答案
根据你想从表中提取的内容,这里是你如何处理数据
numLines <- R.utils::countLines("sportsdb_sample_mysql_20080303.sql")
# [1] 81266
linesInDB <- readLines("sportsdb_sample_mysql_20080303.sql",n=60)
然后你可以做一些正则表达式来获取表名(在 CREATE TABLE 之后)、列名(在第一个括号之间)和 VALUES(在 CREATE TABLE 之后和第二个括号之间的行)
编辑:针对 OP 的回答,如果我正确解释 python 脚本,它也会逐行读取它,过滤 INSERT INTO 行,解析为 csv,然后写入文件。这与我最初的建议非常相似。我的版本在 R 中。如果文件太大,最好使用其他 R 包分 block 读取文件
options(stringsAsFactors=F)
library(utils)
library(stringi)
library(plyr)
mysqldumpfile <- "sportsdb_sample_mysql_20080303.sql"
allLines <- readLines(mysqldumpfile)
insertLines <- allLines[which(stri_detect_fixed(allLines, "INSERT INTO"))]
allwords <- data.frame(stri_extract_all_words(insertLines, " "))
d_ply(allwords, .(X3), function(x) {
#x <- split(allwords, allwords$X3)[["baseball_offensive_stats"]]
print(x[1,3])
#find where the header/data columns start and end
valuesCol <- which(x[1,]=="VALUES")
lastCols <- which(apply(x, 2, function(y) all(is.na(y))))
datLastCol <- head(c(lastCols, ncol(x)+1), 1) - 1
#format and prepare for write to file
df <- data.frame(x[,(valuesCol+1):datLastCol])
df <- setNames(df, x[1,4:(valuesCol-1)])
#type convert before writing to file otherwise its all strings
df[] <- apply(df, 2, type.convert)
#write to file
write.csv(df, paste0(x[1,3],".csv"), row.names=F)
})
关于mysql - 将 MySQL 转储导入 R(不需要 MySQL 服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36738301/
我正在为我的应用程序使用 Tank-Auth。我唯一的问题是激活和重置帐户密码。 用于登录、注册、注销;我对这些代码没有问题; $route['login'] = "/auth/login"; $ro
我是一名优秀的程序员,十分优秀!