How do I create an Sqlite3 database using luasql? - database

I am trying to create a Sqlite3 database with luasql. After I require luasql.sqlite3, how do I create the database on a file?
Also, I can't seem to find the manual for luasql. Is it available anywhere?

SQLLite will create the db automatically if it does not exist.
Here is a set of Sample functions for using it in Lua (ignore the fh functions they are just internal to the program I use).
require 'luasql.sqlite3'
function opendb(dbname)
-- Check for Settings Database and create if needed
local db = fhGetPluginDataFileName()
local dbenv = assert (luasql.sqlite3())
-- connect to data source, if the file does not exist it will be created
dbcon = assert (dbenv:connect(db))
-- check table for page list
checkTable(dbcon,'pagelist',
[[CREATE TABLE pagelist(filename varchar(500), md5hash varchar(32),UNIQUE (filename))
]])
-- create table for settings
checkTable(dbcon,'settings',
[[CREATE TABLE settings(key varchar(20), directory varchar(500),
host varchar(500), folder varchar(50), userid varchar(50), password varchar(50), UNIQUE (key))
]])
return dbenv,dbcon
end
function checkTable(dbcon,table,createString)
local sql = string.format([[SELECT count(name) as count FROM sqlite_master WHERE type='table' AND name='%s']],table)
local cur = assert(dbcon:execute(sql))
local rowcount = cur:fetch (row, "a")
cur:close()
if tonumber(rowcount) == 0 then
-- Table not found create it
res,err = assert(dbcon:execute(createString))
end
end
function closedb(dbenv,dbcon)
dbcon:close()
dbenv:close()
end
function loadSettings(dbcon)
local sql = [[SELECT * FROM settings]]
local cur,err = assert(dbcon:execute(sql))
local row = cur:fetch({},'a')
cur:close()
if row then
return row
else
-- return default values
return {
directory = fhGetContextInfo('CI_PROJECT_PUBLIC_FOLDER')..'\\FH Website',
host = 'websitehost',
folder = '/',
userid = 'user',
password = 'password',
new = 'yes'
}
end
end
function saveSettings(dbcon,settings)
-- Check for Settings
if settings.new == 'yes' then
-- Create
sql = string.format([[insert into settings (directory, host, folder, userid, password) Values('%s','%s','%s','%s','%s')]],settings.directory,settings.host,settings.folder,settings.userid,settings.password)
else
-- Update
sql = string.format([[update settings set directory = '%s', host = '%s',folder = '%s',userid = '%s', password = '%s']],settings.directory,settings.host,settings.folder,settings.userid,settings.password)
end
local res = assert(dbcon:execute(sql))
end

Related

from which database comes a .idb format?

I want to import to read and convert a database in .idb format . I was told that this file comes from a IBM tool used on indows 98. I do not know exactly from which tool.
I have the following files
a .idb file of 1Go size which was called directly by the application using this database with this call procedure
SERVER NAME=localhost:C:\BELAIR3\APPSER\APPSER.IDB
a .db file
a .lck file
a .mb file
a .px file
a .sql file with some procedures, here is the beginning:
CONNECT "localhost:C:\BELAIR3\appser\APPSER.IDB"
USER SYSDBA PASSWORD masterkey;
set term ^ ;
CREATE PROCEDURE CHERCHENOMDPP(
NUMERO INTEGER
)
RETURNS (
NOMDPP VARCHAR(50)
)
AS
DECLARE VARIABLE vnom VARCHAR(50);
DECLARE VARIABLE vprenom VARCHAR(50);
DECLARE VARIABLE vnombre INTEGER;
BEGIN
SELECT b_nom,b_prenom FROM DPPSER
WHERE b_numdpp = :numero
INTO :vnom, :vprenom;
if (vnom is null) then
nomdpp = "???";
else if (vprenom is null) then
nomdpp = vnom;
else
nomdpp = vnom||" "||vprenom;
SUSPEND;
END ^

Manipulating the list of data from stored procedure to be used in another stored procedure

Currently I'm writing a stored procedureusing T-SQL in SQL Server. My script contains code to run another stored procedure to get list of data from a table. I want to manipulate the data, using the list of data to modify them for another purpose (e.g. summing up a column and adding more lists of data) from the stored procedure. A way that I know is to create a temporary table. But after that, I'm not so sure. Please help. thanks.
This is my code:
ALTER PROCEDURE [dbo].[AJU_Rpt_ARAgingSp]
(#Slsman_Starting slsmantype = NULL,
#Slsman_Ending slsmantype = NULL,
#Custnum_Starting custnumtype = NULL,
#Custnum_Ending custnumtype = NULL,
#CustType endusertypetype = NULL,
#CutOff_Date datetype = NULL,
#SumToCorp ListYesNoType = NULL, -- >> 0 = individual, 1 = corp customer
#ShowActive ListYesNoType = NULL, -- >> 0 = all trx, 1 = active only
#TransDomCurr ListYesNoType = NULL, -- >> 0 = dont convert, 1 = convert to local currency
#AgingBasis ArAgeByType = NULL, -->> i = invoice date, d = due date
#LeftToRight ListYesNoType = NULL, -- >> 0 = right to left, 1 = left to right
#CurrSite NVARCHAR(8),
#ShowDetailInfo NVARCHAR(1) = NULL)
AS
BEGIN
SET NOCOUNT ON
IF ISNULL(#CurrSite ,'') = ''
SET #CurrSite = (SELECT TOP 1 site_ref FROM parms_mst)
DECLARE #v_StartDate DateType
SET #Slsman_Starting = ISNULL(#Slsman_Starting, dbo.LowCharacter())
SET #Slsman_Ending = ISNULL(#Slsman_Ending, dbo.HighCharacter())
SET #Custnum_Starting = ISNULL(#Custnum_Starting, dbo.LowCharacter())
SET #Custnum_Ending = ISNULL(#Custnum_Ending, dbo.HighCharacter())
SET #v_StartDate = dbo.LowDate()
SET #CutOff_Date = GETDATE()
EXEC dbo.ApplyDateOffsetSp #v_StartDate OUT, NULL, 0
EXEC AJU_Rpt_DebtorSp
#CustNumStart = #Custnum_Starting
,#CustNumEnd = #Custnum_Ending
,#DistDateStart = #v_StartDate
,#DistDateEnd = #CutOff_Date
,#CurrCodeStart = NULL
,#CurrCodeEnd = NULL
,#SlsmanStart = #Slsman_Starting
,#SlsmanEnd = #Slsman_Ending
,#TerritoryStart = NULL
,#TerritoryEnd = NULL
,#CustTypeStart = NULL
,#CustTypeEnd = NULL
,#SiteGroup = #CurrSite
,#ConsolidatePayment = NULL
,#DisplayResult = 1
END
Since the initial result table is temporarily needed, you could do as follows:
In the invoking procedure, create a table variable with identical structure as returned by the invoked procedure,
Write within the invoking procedure a statement like the following:
INSERT INTO #_Tempo_Table
EXEC Invoked_Procedure (<params>) ;
Within the invoked procedure issue a SELECT that will return the records set.
If, in the other hand, you need to pass the initial table to the invoked procedure:
Create a type with a structure identical to the table that needs to be shared,
Add to the invoked procedure an argument of the type you just created (must be declared as READONLY),
Once you have the table with data within the invoking procedure, make the call to the invoked procedure passing the table variable as argument.
This methods will render the best performance (here I'm assuming that you are not passing a table with millions of records; if you do, it will still be the fastest way though you might need a lot of memory).

How to specify a destination DB while exporting data frame to mssql

I would like to export a data frame to mssql table.I used the code below but I would like to set the destination and not only the server and table name.I have a few DBs inside the server,how can i save the table in one of them?
df<-read.csv(file.choose(),header = T,sep= T)
DB= odbcConnect(dsn ='R_BISRV',uid = 'XXXX', pwd = 'XXX')
sqlSave(DB, df, tablename = 'Tanya', rownames = F,append = T)
close(DB)
I figured it out:
Data base name should be in the odbcDriverConnect() and table name in the sqlSave()
channel <- odbcDriverConnect('driver={SQL Server};server=YYY;database=YY;port=1433;
uid=XX;pwd=XXX')
# Client systems use TCP 1433 to connect to the database engine
sqlSave(channel = channel,dat = df, rownames = TRUE, tablename = "Tanya")

can corona be able to open an MySQL DB?

just wondering, if MySQL can be used in corona or MySQL db's can be opened using sqlite3
or is there any difference If I use a MySQL db or sqlite3 db?
Corona provides its own library for connection to SQLite drivers, whose document can be accessed here.
local sqlite3 = require "sqlite3"
--Open data.db. If the file doesn't exist it will be created
local path = system.pathForFile("data.db", system.DocumentsDirectory)
db = sqlite3.open( path )
--Handle the applicationExit event to close the db
local function onSystemEvent( event )
if( event.type == "applicationExit" ) then
db:close()
end
end
--Setup the table if it doesn't exist
local tablesetup = [[CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, content, content2);]]
print(tablesetup)
db:exec( tablesetup )
--Add rows with a auto index in 'id'. You don't need to specify a set of values because we're populating all of them
local testvalue = {}
testvalue[1] = 'Hello'
testvalue[2] = 'World'
testvalue[3] = 'Lua'
local tablefill =[[INSERT INTO test VALUES (NULL, ']]..testvalue[1]..[[',']]..testvalue[2]..[['); ]]
local tablefill2 =[[INSERT INTO test VALUES (NULL, ']]..testvalue[2]..[[',']]..testvalue[1]..[['); ]]
local tablefill3 =[[INSERT INTO test VALUES (NULL, ']]..testvalue[1]..[[',']]..testvalue[3]..[['); ]]
db:exec( tablefill )
db:exec( tablefill2 )
db:exec( tablefill3 )
--print the sqlite version to the terminal
print( "version " .. sqlite3.version() )
--print all the table contents
for row in db:nrows("SELECT * FROM test") do
local text = row.content.." "..row.content2
local t = display.newText(text, 20, 30 * row.id, null, 16)
t:setFillColor( 1, 0, 1 )
end
--setup the system listener to catch applicationExit
Runtime:addEventListener( "system", onSystemEvent )
You can also use third party libraries (or batteries) for creating connections. One such library common in use is LuaSQL.
A thread on the Corona community shows you how to establish connection using LuaSQL for MySQL servers.
local luasql = require "luasql.mysql";
env = assert((luasql.mysql()), "Uh oh, couldn't load driver")
conn = assert(env:connect("database","username","password","localhost"), "Oops!!")
cur = assert (conn:execute ("SELECT * from table_1" ))
row = cur:fetch ({}, "a")
while row do
print ("\n------ new row ---------\n")
table.foreach (row, print)
row = cur:fetch (row, "a")
end
cur:close()
conn:close()
env:close()

Strange behaviour execute SQL Server from .NET to CREATE tables or columns

I have a big SQL text file where I have a lot of SQL commands to create tables, columns, etc.
Example row(s):
IF NOT EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = object_id(N'xcal_views') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE xcal_views (lid INT NOT NULL);
GO
IF NOT EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = object_id(N'xcal_views_actors') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE xcal_views_actors (lid INT NOT NULL);
GO
IF NOT EXISTS ( SELECT * FROM dbo.syscolumns, dbo.sysobjects WHERE [dbo].[syscolumns].[name] = 'xlactor' AND [dbo].[sysobjects].[id] = [dbo].[syscolumns].[id] AND [dbo].[sysobjects].[id] = object_id(N'xcal_views_actors') AND OBJECTPROPERTY([dbo].[sysobjects].[id], N'IsUserTable') = 1 )
ALTER TABLE [dbo].[xcal_views_actors] ADD xlactor INT NULL;
GO
IF NOT EXISTS ( SELECT * FROM dbo.syscolumns, dbo.sysobjects WHERE [dbo].[syscolumns].[name] = 'lparentid' AND [dbo].[sysobjects].[id] = [dbo].[syscolumns].[id] AND [dbo].[sysobjects].[id] = object_id(N'xcal_views_actors') AND OBJECTPROPERTY([dbo].[sysobjects].[id], N'IsUserTable') = 1 )
ALTER TABLE [dbo].[xcal_views_actors] ADD lparentid INT NULL;
GO
IF NOT EXISTS ( SELECT * FROM dbo.sysobjects WHERE parent_obj = (SELECT id FROM dbo.sysobjects WHERE id = object_id(N'xcal_views_actors') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) AND OBJECTPROPERTY(id, N'IsPrimaryKey') = 1)
ALTER TABLE [dbo].[xcal_views_actors]
ADD CONSTRAINT [CT_00000501] PRIMARY KEY CLUSTERED (lid ASC);
GO
IF NOT EXISTS ( SELECT * FROM [sys].[indexes] i INNER JOIN [sys].[objects] o ON o.object_id = i.object_id AND o.name = 'xcal_views_actors' WHERE i.name = 'parent_id' )
CREATE INDEX parent_id ON xcal_views_actors (lparentid ASC)
GO
Between each command I have a GO in extra line to separate the commands.
If I run the whole patch.sql file from SQL Server Management Studio all commands are executed and works fine.
In .NET I read the whole text file, then split them with 'GO' and execute each SQL command against the database.
Now the strange thing: some of the commands don't get executed. And I can't find out why.
This is the method that does the job:
private static void patchDatabase(string connection, string sqlfile)
{
var defaultEncoding = Encoding.Default;
using (FileStream fs = File.OpenRead(sqlfile))
{
defaultEncoding = TextFileEncodingDetector.DetectTextFileEncoding(fs, defaultEncoding, 1024);
}
//Console.WriteLine(string.Format("File {0} using encoding: {1}",sqlfile, defaultEncoding));
var dbPatch = new StreamReader(sqlfile, defaultEncoding);
string sqlPatch = dbPatch.ReadToEnd();
dbPatch.Close();
string[] stringSeparators = new[] {"GO"};
string[] sqlPatches = sqlPatch.Split(stringSeparators, StringSplitOptions.None);
if (connection != null && sqlPatch.Length > 0)
{
Console.WriteLine(string.Format("Executing {0} statements from {1}", sqlPatches.Length, sqlfile));
using (var cnn = new SqlConnection(connection))
{
cnn.Open();
foreach (var sql in sqlPatches)
{
if (String.IsNullOrEmpty(sql))
continue; // Not a real sql statement, use next
using (var cmd = new SqlCommand(sql, cnn))
{
try
{
cmd.CommandTimeout = 120;
cmd.ExecuteNonQuery();
//int results = cmd.ExecuteNonQuery();
//if (results < 1)
// Console.WriteLine(String.Format("Failed:\nResult: {0}\n{1}",results, sql));
}
catch (Exception ex)
{
Console.WriteLine("Execution error!\n\n" + sql + "\n\n\n" + ex);
}
}
}
cnn.Close();
}
}
}
It looks like my function splutters...
My current textfile has around 6.000+ lines.
Any idea what I do wrong?
It looks like it wasn't a coding problem at all.
In fact I produced the following situation:
I have a database "test_db"
I create a user "test_db_user" and make him db_owner
He is added in sql server in general "security - roles" with objekt "test_db" as role db_owner
He also gets added as user in the database "test_db" - security - user.
Now it comes: I restored the database again after some tests.
The user is not anymore listed in "test_db" - security - user
but still configured as db_owner in general.
Somehow the connection works then but it don't has not full access to the db all the time. Can't really know what is going wrong.
From the management studio I ever used admin account for starting the sql batches, that is the reason it worked all the time there.
So solution: Make sure the security settings are 100% correct and then it works :S
Another problem was my stupidity :S!!! I had some create table statements without dbo. schema before the table so the different user created a different schema name for the table.
Thanks to all for the feedback.

Resources