Class: Daru::IO::Exporters::SQL

Inherits:
Base
  • Object
show all
Defined in:
lib/daru/io/exporters/sql.rb

Overview

SQL Exporter Class, that extends to_sql method to Daru::DataFrame instance variables

Instance Method Summary collapse

Methods inherited from Base

#optional_gem

Constructor Details

#initialize(dataframe, dbh, table) ⇒ SQL

Initializes a SQL Exporter instance.

Examples:

Initializing with database credentials

df = Daru::DataFrame.new([[1,2],[3,4]], order: [:a, :b])

#=> #<Daru::DataFrame(2x2)>
#      a   b
#  0   1   3
#  1   2   4

table = 'test'

dbh = DBI.connect("DBI:Mysql:database:localhost", "user", "password")
# Enter the actual SQL database credentials in the above line

instance = Daru::IO::Exporters::SQL.new(df, dbh, table)

Parameters:

  • dataframe (Daru::DataFrame)

    A dataframe to export.

  • dbh (DBI)

    A DBI database connection object.

  • table (String)

    The SQL table to export to.



31
32
33
34
35
36
37
38
39
# File 'lib/daru/io/exporters/sql.rb', line 31

def initialize(dataframe, dbh, table)
  optional_gem 'dbd-sqlite3', requires: 'dbd/SQLite3'
  optional_gem 'dbi'
  optional_gem 'sqlite3'

  super(dataframe)
  @dbh       = dbh
  @table     = table
end

Instance Method Details

#toObject

Exports a SQL Exporter instance to an SQL table.

Examples:

Exports SQL Exporter instance into given SQL table

instance.to


45
46
47
48
49
50
51
# File 'lib/daru/io/exporters/sql.rb', line 45

def to
  query = "INSERT INTO #{@table} (#{@dataframe.vectors.to_a.join(',')}"\
          ") VALUES (#{(['?']*@dataframe.vectors.size).join(',')})"
  sth   = @dbh.prepare(query)
  @dataframe.each_row { |c| sth.execute(*c.to_a) }
  true
end