Created
November 8, 2024 23:24
-
-
Save cesc1989/9f2dc7c4bf4a281c49aab7173fd34dce to your computer and use it in GitHub Desktop.
Crea una base de datos SQLite a partir de un archivo CSV.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "csv" | |
require "sqlite3" | |
if ARGV.length < 3 | |
puts "Uso: ruby create_db_from_csv.rb ruta/al/archivo.csv debugging.dashboard.db nombre_tabla" | |
exit | |
end | |
csv_file = ARGV[0] | |
db_file = ARGV[1] | |
table_name = ARGV[2] | |
db = SQLite3::Database.new(db_file) | |
columns = nil | |
CSV.foreach(csv_file, headers: true) do |row| | |
columns = row.headers.map { |col| "#{col} TEXT" } | |
break | |
end | |
db.execute("DROP TABLE IF EXISTS #{table_name}") | |
db.execute("CREATE TABLE #{table_name} (#{columns.join(', ')})") | |
CSV.foreach(csv_file, headers: true) do |row| | |
placeholders = Array.new(row.size, "?").join(", ") | |
db.execute("INSERT INTO #{table_name} VALUES (#{placeholders})", row.fields) | |
end | |
db.close | |
puts "Base de datos #{db_file} creada con la tabla #{table_name} a partir del archivo CSV." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment