Pasting Values in SQL Query through R - sql

I have the following dataframe which contains the AxiomaID.
x<-c(0123, 234, 2348, 345, 3454)
And trying to run the following SQL Query within R.
SQL6<-data.frame(sqlQuery(myConn, "SELECT top 10 [AxiomaDate]
,[RiskModelID]
,[AxiomaID]
,[Factor1]
FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
Where AxiomaID = x"))
How can I paste all the x values which contain the AxiomaID's into the SQL Query?

Try the following query:
SQL6<-data.frame(sqlQuery(myConn, paste("SELECT top 10 [AxiomaDate]
,[RiskModelID]
,[AxiomaID]
,[Factor1]
FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
Where AxiomaID IN (", paste(x, collapse = ", "), ")")))
Hope it helps!

You would try a function like
InsertListInQuery <- function(querySentence, InList) {
InValues <- ""
for (i in 1:length(InList)){
if (i < length(InList)) {
InValues <- paste(InValues,InList[[i]],",")}
else {
InValues <- paste(InValues,InList[[i]],sep = "")
}
}
LocOpenParenthesis <- gregexpr('[(]', querySentence)[[1]][[1]]
LocCloseParenthesis <- gregexpr('[)]', querySentence)[[1]][[1]]
if (LocCloseParenthesis-LocOpenParenthesis==1) {
querySentence<- gsub("[(]", paste("(",InValues,sep = ""), querySentence)
}
return (querySentence )
}
Function InsertListInQuery requires you to change your original query to one that use constraint IN () in WHERE clausule. What function does is to conform a string with vector elements separated by comma, and replace "(" string with the one composed. Finally, return a character variable.
Hence, you can define your vector of constraints list of elements, your query and call the function as shown:
x<-c(0123, 234, 2348, 345, 3454)
query <- "SELECT top 10 [AxiomaDate]
,[RiskModelID]
,[AxiomaID]
,[Factor1]
FROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]
Where AxiomaID IN ()"
finalQuery <- InsertListInQuery(query, x)
Value of finalQuery is:
finalQuery
[1] "SELECT top 10 [AxiomaDate] \n ,[RiskModelID]\n,[AxiomaID]\n,[Factor1]\nFROM [PortfolioAnalytics].[Data_Axioma].[SecurityExposures]\nWhere AxiomaID IN ( 123 , 234 , 2348 , 345 ,3454)"
Note the line return with special character \n.
I hope it may help.

Related

How to change equal (=) to not equal to (<>) in postgres using Go

I have two sql querys that are very similar. The only difference is that in one of the WHERE clauses I am using equal to (=) instead of not equal to (<>). Is there a way to modify the query programmatically in an elegant way? I am looking for something like this:
func getEvents(name string, exclude bool) {
q := `SELECT * FROM events WHERE name`
if exclude {
q = q + " <> "
} else {
q = q + " = "
}
q = q + "$1"
result, err := DBQuery(q, name)
...
}
One elegant way would be to create a type and constants for the operators:
type Op string
const (
OpEqual Op = "="
OpNotEqual Op = "<>"
OpLessThan Op = "<"
OpGreaterThan Op = ">"
// ... any other ops you need
)
And then building the query string is a simple string concatenation:
q := "SELECT * FROM events WHERE name" + op + "$1"
Or you may use fmt.Sprintf():
q := fmt.Sprintf("SELECT * FROM events WHERE name %s $1", op)
Of course change signature of getEvents() to:
func getEvents(name string, op Op)
And calling getEvents() is now even nicer:
getEvents("error", OpEqual)
getEvents("error", OpNotEqual)
Try the examples on the Go Playground.

How to dynamically generate SQL query column names and values from arrays?

I have about 20 columns in one row and not all columns are required to be filled in when row created also i dont want to cardcode name of every column in SQL query and on http.post request on frontend. All values are from form. My code:
var colNames, values []string
for k, v := range formData {
colNames = append(colNames, k)
values = append(values, v)
}
Now i have 2 arrays: one with column names and second with values to be inserted. I want to do something like this:
db.Query("insert into views (?,?,?,?,?,?) values (?,?,?,?,?,?)", colNames..., values...)
or like this:
db.Query("insert into views " + colNames + " values" + values)
Any suggestions?
Thanks!
I assume your code examples are just pseudo code but I'll state the obvious just in case.
db.Query("insert into views (?,?,?,?,?,?) values (?,?,?,?,?,?)", colNames..., values...)
This is invalid Go since you can only "unpack" the last argument to a function, and also invalid MySQL since you cannot use placeholders (?) for column names.
db.Query("insert into views " + colNames + " values" + values)
This is also invalid Go since you cannot concatenate strings with slices.
You could fromat the slices into strings that look like this:
colNamesString := "(col1, col2, col3)"
valuesString := "(val1, val2, val3)"
and now your second code example becomes valid Go and would compile but don't do this. If you do this your app becomes vulnerable to SQL injection and that's something you definitely don't want.
Instead do something like this:
// this can be a package level global and you'll need
// one for each table. Keep in mind that Go maps that
// are only read from are safe for concurrent use.
var validColNames = map[string]bool{
"col1": true,
"col2": true,
"col3": true,
// ...
}
// ...
var colNames, values []string
var phs string // placeholders for values
for k, v := range formData {
// check that column is valid
if !validColNames[k] {
return ErrBadColName
}
colNames = append(colNames, k)
values = append(values, v)
phs += "?,"
}
if len(phs) > 0 {
phs = phs[:len(phs)-1] // drop the last comma
}
phs = "(" + phs + ")"
colNamesString := "(" + strings.Join(colNames, ",") + ")"
query := "insert into views " + colNamesString + phs
db.Query(query, values...)

R, Call a SQL Server stored procedure with RJDBC

I would like to call a stored procedure from a function in R. See my code below. unfortunately this code only generates a dataframe without values in it. I would like to fix this with RJDBC&DBI, since there seems to be a problem with RODBC.
RPT_09_Hourly_Connected_v3<- function(Year, Month="NULL",State = "NULL",Region="NULL", City="NULL", District="NULL", Subdistrict="NULL" ,Address='NULL'){
drv <- JDBC("com.microsoft.sqlserver.jdbc.SQLServerDriver", "/opt/sqljdbc_3.0/sqljdbc4.jar")
conn <- DBI::dbConnect(drv, "jdbc:sqlserver://***;databaseName=***;user=***;password=***")
sqlText <- paste("exec [dbo].[RPT_09_Hourly_Connected_v3]#Year=",Year,
",#Month=",Month,
",#State=",State,"",
",#Region=",Region,"",
",#City=N'",City,"'",
",#District=",District,"",
",#Subdistrict=",Subdistrict,"",
",#Address=N'",Address,"'",
sep="")
data <- RJDBC::dbGetQuery(conn,sqlText)
}
a<- RPT_09_Hourly_Connected_v3(Year = 2016)
> str(a)
'data.frame': 0 obs. of 9 variables:
$ Regio : chr
$ Stad : chr
$ Stadsdeel : chr
$ Buurtcombinatie: chr
$ Adres : chr
$ Jaar : num
$ Maand : num
$ hourNR : num
$ HoursConnected : num
This worked for me before RODBC crashed. Is there any difference between RODBC and RJDBC?
RPT_09_Hourly_Connected_v3<- function(Year, Month="NULL",State = "NULL",Region="NULL", City="NULL", District="NULL", Subdistrict="NULL" ,Address='NULL'){
dbhandle <- odbcConnect("***;DATABASE=***;UID=***;PWD=***")
data <- sqlQuery(dbhandle,paste("exec [ dbo].[RPT_09_Hourly_Connected_v3]#Year=",Year,
",#Month=",Month,
",#State=",State,"",
",#Region=",Region,"",
",#City=N'",City,"'",
",#District=",District,"",
",#Subdistrict=",Subdistrict,"",
",#Address=N'",Address,"'",
sep=""))
odbcCloseAll()
data
}
If I execute the stored procedure in SQL Server by hand it will look like this:
EXEC #return_value = [dbo].[RPT_09_Hourly_Connected_v3]
#Year = 2016,
#Month = NULL,
#State = NULL,
#Region = NULL,
#City = N'Amsterdam',
#District = NULL,
#Subdistrict = NULL,
#Address = NULL
Can you explain what's wrong and how to fix it?
I find the RODBCext a lot easier to use since it uses parameter binding. It also makes it easier to use NA in place of "NULL" and eliminates the concern about matching up the quote characters correctly.
library(RODBCext)
RPT_09_Hourly_Connected_v3<- function(Year, Month=NA, State = NA, Region=NA, City=NA, District=NA, Subdistrict=NA ,Address=NA){
ch <- odbcDriverConnect([connection_string])
sqlText <- paste("exec [dbo].[RPT_09_Hourly_Connected_v3]#Year=? ",
",#Month=? ",
",#State=? ",
",#Region=? ",
",#City=? ",
",#District=? ",
",#Subdistrict=? ",
",#Address=? ",
sep="")
sqlExecute(channel = ch,
query = sqlText,
data = list(Year, Month, State, Region, City, District, Subdistrict, Address),
fetch = TRUE,
stringAsFactors = FALSE)
}
I found a very easy solution, and I wish I knew this before! Maybe I can help someone else with my answer.
FACT_CHARGESESSION<- function (username, password, country = "NULL",state = "NULL", region = "NULL",city = "NULL",
district = "NULL",subdistrict = "NULL", provider= "NULL",startDateView = "NULL",endDateView = "NULL") {
InstallCandidates <-c("DBI","rJava","RJDBC","dplyr")
toInstall<-InstallCandidates[!InstallCandidates %in% library()$results[,1]]
if(length(toInstall) !=0){install.packages(toInstall,repos="http://cran.r-project.org")}
lapply(InstallCandidates,library,character.only=TRUE)
rm("InstallCandidates","toInstall")
NAME <- "dbo.R_00_ValidTransactions_ID_PW_v4"
options(java.parameters = "- Xmx1024m")
drv <- JDBC("com.microsoft.sqlserver.jdbc.SQLServerDriver", "/opt/sqljdbc_3.0/sqljdbc4.jar")
conn <- dbConnect(drv, "jdbc:sqlserver://***.**.***.***;databaseName=****;user=***;password=***")
# Make a SQL text
sqlText <- paste(NAME, paste(username,password, country,state,region,city,district,subdistrict,provider,startDateView,endDateView,sep=","))
data <- dbGetQuery(conn,sqlText)
return(data)
}
output of sqlText:
"dbo.R_00_ValidTransactions_ID_PW_v4 M.Kooi , Stackoverflow , NULL , NULL , Amsterdam , NULL , NULL , NULL , NULL , NULL , NULL "
Instead of using the SP execute window you just execute now the SP with the paremters in a new query window.
I've used this in the past successfully with RJDBC:
d <- dbGetQuery(conn, paste0("exec my_STOREDPROC #Field1= '",Field1,"';"))
It might be simply a matter of syntax. Hard to tell w/o a reproducible example. Note the extra set of quotes.

SQL Query Error when selecting separate columns

I do not understand the error which appears in my SQL Query. If i choose in SQL
Select * -> it is working fine and i do get the table,
however if i select any of the column/s it is giving me an Error:
Error in $<-.data.frame(*tmp*, "PROBE", value =
structure(integer(0), .Label = character(0), class = "factor")) :
replacement has 0 rows, data has 1427
Here is my SQL code:
if(input$filter == 1){
sqlOutput <- reactive({
sqlInput <- paste("select * from DWH.PROBE where DWH.PROBE.Nr =",paste0("'",d(),"'"), "And DWH.PROBE.AB BETWEEN",input$abmfrom, "AND",input$abmto,"ORDER BY Datum asc")
print(sqlInput)
dbGetQuery(con$cc, sqlInput)
})
}else{
sqlOutput <- reactive({
sqlInput <- paste("select * from DWH.PROBE where DWH.PROBE.S BETWEEN",d2(), "AND",input$sgehalt2, "And DWH.PROBE.AB BETWEEN",input$abmfrom2, "AND",input$abmto2,"ORDER BY Datum asc")
dbGetQuery(con$cc, sqlInput)
})}
And if i just add to those SQL Queries
select DWH.PROBE.S, DWH.PROBE.AB.. from DWH.PROBE
Then it comes above mentioned Error.
Additionally i need to say if i will use this SQL Query in a simple code:
rs <- dbSendQuery(con, paste("select DWH.PROBE.AB, DWH.PROBE.S from DWH.PROBE where DWH.PROBE.Nr = '50' And DWH.PROBE.AB BETWEEN 40 AND 50 ORDER BY Datum asc"))
data <- fetch(rs)
It is giving me the results...
Any ideas?
[EDIT *as my question is not a duplicate]
The question posted here: http://stackoverflow.com/questions/32048072/how-to-pass-input-variable-to-sql-statement-in-r-shiny actually has nothing to do with my topic. As we can see the error in this post:
Error in .getReactiveEnvironment()$currentContext() : Operation not
allowed without an active reactive context. (You tried to do something
that can only be done from inside a reactive expression or observer.)
I do not have a problems with passing input variable to sql statement and additionally if you can see in my SQL: The Query is in reactive context!:
sqlOutput <- reactive({...
The solution for above question was:
to put SQL Query in reactive context which is not a thing in my case
[EDIT 2] -> bits related to sqlOutput()
Here is a bit of code related to sqlOutput() which i am using in my Shiny App (at the moment this is the only bit because i am stuck with SQL Query)
output$tabelle <- DT::renderDataTable({
data <- sqlOutput()
data$PROBE <- as.factor(as.character(data$PROBE))
data
}, rownames=TRUE, filter="top", class = 'cell-border stripe',
options = list(pageLength = 100, lengthMenu=c(100,200,500), columnDefs = list(list(width = '200px', targets = "_all"),list(bSortable = FALSE, targets = "_all"))))
Thanks
Error doesn't relate to SQL statements, however, try changing your code to below:
sqlOutput <- reactive({
if(input$filter == 1){
sqlInput <- paste("select * from DWH.PROBE where DWH.PROBE.Nr =",paste0("'",d(),"'"), "And DWH.PROBE.AB BETWEEN",input$abmfrom, "AND",input$abmto,"ORDER BY Datum asc")
} else {
sqlInput <- paste("select * from DWH.PROBE where DWH.PROBE.S BETWEEN",d2(), "AND",input$sgehalt2, "And DWH.PROBE.AB BETWEEN",input$abmfrom2, "AND",input$abmto2,"ORDER BY Datum asc")
}
dbGetQuery(con$cc, sqlInput)
})

How to get a list of column names on Sqlite3 database?

I want to migrate my iPhone app to a new database version. Since I don't have some version saved, I need to check if certain column names exist.
This Stackoverflow entry suggests doing the select
SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'
and parse the result.
Is that the common way? Alternatives?
PRAGMA table_info(table_name);
will get you a list of all the column names.
If you do
.headers ON
you will get the desired result.
If you have the sqlite database, use the sqlite3 command line program and these commands:
To list all the tables in the database:
.tables
To show the schema for a given tablename:
.schema tablename
Just for super noobs like me wondering how or what people meant by
PRAGMA table_info('table_name')
You want to use use that as your prepare statement as shown below. Doing so selects a table that looks like this except is populated with values pertaining to your table.
cid name type notnull dflt_value pk
---------- ---------- ---------- ---------- ---------- ----------
0 id integer 99 1
1 name 0 0
Where id and name are the actual names of your columns. So to get that value you need to select column name by using:
//returns the name
sqlite3_column_text(stmt, 1);
//returns the type
sqlite3_column_text(stmt, 2);
Which will return the current row's column's name. To grab them all or find the one you want you need to iterate through all the rows. Simplest way to do so would be in the manner below.
//where rc is an int variable if wondering :/
rc = sqlite3_prepare_v2(dbPointer, "pragma table_info ('your table name goes here')", -1, &stmt, NULL);
if (rc==SQLITE_OK)
{
//will continue to go down the rows (columns in your table) till there are no more
while(sqlite3_step(stmt) == SQLITE_ROW)
{
sprintf(colName, "%s", sqlite3_column_text(stmt, 1));
//do something with colName because it contains the column's name
}
}
If you want the output of your queries to include columns names and be correctly aligned as columns, use these commands in sqlite3:
.headers on
.mode column
You will get output like:
sqlite> .headers on
sqlite> .mode column
sqlite> select * from mytable;
id foo bar
---------- ---------- ----------
1 val1 val2
2 val3 val4
An alternative way to get a list of column names not mentioned here that is cross platform and does not rely on the sqlite3.exe shell is to select from the PRAGMA_TABLE_INFO() table value function.
SELECT name FROM PRAGMA_TABLE_INFO('your_table');
name
tbl_name
rootpage
sql
You can check if a certain column exists by querying:
SELECT 1 FROM PRAGMA_TABLE_INFO('your_table') WHERE name='column1';
1
This is what you use if you don't want to parse the result of select sql from sqlite_master or pragma table_info.
Note this feature is experimental and was added in SQLite version 3.16.0 (2017-01-02).
Reference:
https://www.sqlite.org/pragma.html#pragfunc
To get a list of columns you can simply use:
.schema tablename
I know it is an old thread, but recently I needed the same and found a neat way:
SELECT c.name FROM pragma_table_info('your_table_name') c;
When you run the sqlite3 cli, typing in:
sqlite3 -header
will also give the desired result
.schema table_name
This will list down the column names of the table from the database.
Hope this will help!!!
you can use Like statement if you are searching for any particular column
ex:
SELECT * FROM sqlite_master where sql like('%LAST%')
This command below sets column names:
.header on
Then, this is how it looks like below:
sqlite> select * from user;
id|first_name|last_name|age
1|Steve|Jobs|56
2|Bill|Gates|66
3|Mark|Zuckerberg|38
And this command below unsets column names:
.header off
Then, this is how it looks like below:
sqlite> select * from user;
1|Steve|Jobs|56
2|Bill|Gates|66
3|Mark|Zuckerberg|38
And these commands show the details of the command ".header":
.help .header
Or:
.help header
Then, this is how it looks like below:
sqlite> .help .header
.headers on|off Turn display of headers on or off
In addition, this command below sets the output mode "box":
.mode box
Then, this is how it looks like below:
sqlite> select * from user;
┌────┬────────────┬────────────┬─────┐
│ id │ first_name │ last_name │ age │
├────┼────────────┼────────────┼─────┤
│ 1 │ Steve │ Jobs │ 56 │
│ 2 │ Bill │ Gates │ 66 │
│ 3 │ Mark │ Zuckerberg │ 38 │
└────┴────────────┴────────────┴─────┘
And, this command below sets the output mode "table":
.mode table
Then, this is how it looks like below:
sqlite> select * from user;
+----+------------+------------+-----+
| id | first_name | last_name | age |
+----+------------+------------+-----+
| 1 | Steve | Jobs | 56 |
| 2 | Bill | Gates | 66 |
| 3 | Mark | Zuckerberg | 38 |
+----+------------+------------+-----+
And these commands show the details of the command ".mode":
.help .mode
Or:
.help mode
Then, this is how it looks like below:
sqlite> .help .mode
.import FILE TABLE Import data from FILE into TABLE
Options:
--ascii Use \037 and \036 as column and row separators
--csv Use , and \n as column and row separators
--skip N Skip the first N rows of input
--schema S Target table to be S.TABLE
-v "Verbose" - increase auxiliary output
Notes:
* If TABLE does not exist, it is created. The first row of input
determines the column names.
* If neither --csv or --ascii are used, the input mode is derived
from the ".mode" output mode
* If FILE begins with "|" then it is a command that generates the
input text.
.mode MODE ?OPTIONS? Set output mode
MODE is one of:
ascii Columns/rows delimited by 0x1F and 0x1E
box Tables using unicode box-drawing characters
csv Comma-separated values
column Output in columns. (See .width)
html HTML <table> code
insert SQL insert statements for TABLE
json Results in a JSON array
line One value per line
list Values delimited by "|"
markdown Markdown table format
qbox Shorthand for "box --width 60 --quote"
quote Escape answers as for SQL
table ASCII-art table
tabs Tab-separated values
tcl TCL list elements
OPTIONS: (for columnar modes or insert mode):
--wrap N Wrap output lines to no longer than N characters
--wordwrap B Wrap or not at word boundaries per B (on/off)
--ww Shorthand for "--wordwrap 1"
--quote Quote output text as SQL literals
--noquote Do not quote output text
TABLE The name of SQL table used for "insert" mode
In order to get the column information you can use the following snippet:
String sql = "select * from "+oTablename+" LIMIT 0";
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
ResultSetMetaData mrs = rs.getMetaData();
for(int i = 1; i <= mrs.getColumnCount(); i++)
{
Object row[] = new Object[3];
row[0] = mrs.getColumnLabel(i);
row[1] = mrs.getColumnTypeName(i);
row[2] = mrs.getPrecision(i);
}
//JUST little bit modified the answer of giuseppe which returns array of table columns
+(NSMutableArray*)tableInfo:(NSString *)table{
sqlite3_stmt *sqlStatement;
NSMutableArray *result = [NSMutableArray array];
const char *sql = [[NSString stringWithFormat:#"PRAGMA table_info('%#')",table] UTF8String];
if(sqlite3_prepare(md.database, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement tableInfo %#",
[NSString stringWithUTF8String:(const char *)sqlite3_errmsg(md.database)]);
}
while (sqlite3_step(sqlStatement)==SQLITE_ROW)
{
[result addObject:
[NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)]];
}
return result;
}
.schema
in sqlite console when you have you're inside the table
it looks something like this for me ...
sqlite>.schema
CREATE TABLE players(
id integer primary key,
Name varchar(255),
Number INT,
Team varchar(255)
This is an old question, but here is an alternative answer that retrieves all the columns in the SQLite database, with the name of the associated table for each column :
WITH tables AS (SELECT name tableName, sql
FROM sqlite_master WHERE type = 'table' AND tableName NOT LIKE 'sqlite_%')
SELECT fields.name, fields.type, tableName
FROM tables CROSS JOIN pragma_table_info(tables.tableName) fields
This returns this type of result:
{
"name": "id",
"type": "integer",
"tableName": "examples"
}, {
"name": "content",
"type": "text",
"tableName": "examples"
}
For a simple table containing an identifier and a string content.
function getDetails(){
var data = [];
dBase.executeSql("PRAGMA table_info('table_name') ", [], function(rsp){
if(rsp.rows.length > 0){
for(var i=0; i<rsp.rows.length; i++){
var o = {
name: rsp.rows.item(i).name,
type: rsp.rows.item(i).type
}
data.push(o);
}
}
alert(rsp.rows.item(0).name);
},function(error){
alert(JSON.stringify(error));
});
}
-(NSMutableDictionary*)tableInfo:(NSString *)table
{
sqlite3_stmt *sqlStatement;
NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
const char *sql = [[NSString stringWithFormat:#"pragma table_info('%s')",[table UTF8String]] UTF8String];
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement tableInfo %#",[NSString stringWithUTF8String:(const char *)sqlite3_errmsg(db)]);
}
while (sqlite3_step(sqlStatement)==SQLITE_ROW)
{
[result setObject:#"" forKey:[NSString stringWithUTF8String:(char*)sqlite3_column_text(sqlStatement, 1)]];
}
return result;
}
I know it's too late but this will help other.
To find the column name of the table, you should execute select * from tbl_name and you will get the result in sqlite3_stmt *. and check the column iterate over the total fetched column. Please refer following code for the same.
// sqlite3_stmt *statement ;
int totalColumn = sqlite3_column_count(statement);
for (int iterator = 0; iterator<totalColumn; iterator++) {
NSLog(#"%s", sqlite3_column_name(statement, iterator));
}
This will print all the column names of the result set.
I was able to retrieve table names with corresponding columns by using one sql query, but columns output is comma separated. I hope it helps somebody
SELECT tbl_name, (SELECT GROUP_CONCAT(name, ',') FROM PRAGMA_TABLE_INFO(tbl_name)) as columns FROM sqlite_schema WHERE type = 'table';
Get a list of tables and columns as a view:
CREATE VIEW Table_Columns AS
SELECT m.tbl_name AS TableView_Name, m.type AS TableView, cid+1 AS Column, p.*
FROM sqlite_master m, Pragma_Table_Info(m.tbl_name) p
WHERE m.type IN ('table', 'view') AND
( m.tbl_name = 'mypeople' OR m.tbl_name LIKE 'US_%') -- filter tables
ORDER BY m.tbl_name;
//Called when application is started. It works on Droidscript, it is tested
function OnStart()
{
//Create a layout with objects vertically centered.
lay = app.CreateLayout( "linear", "VCenter,FillXY" );
//Create a text label and add it to layout.
txt = app.CreateText( "", 0.9, 0.4, "multiline" )
lay.AddChild( txt );
app.AddLayout(lay);
db = app.OpenDatabase( "MyData" )
//Create a table (if it does not exist already).
db.ExecuteSql( "drop table if exists test_table" )
db.ExecuteSql( "CREATE TABLE IF NOT EXISTS test_table " +
"(id integer primary key, data text, num integer)",[],null, OnError )
db.ExecuteSql( "insert into test_table values (1,'data10',100),
(2,'data20',200),(3,'data30',300)")
//Get all the table rows.
DisplayAllRows("SELECT * FROM test_table");
DisplayAllRows("select *, id+100 as idplus, 'hahaha' as blabla from
test_table order by id desc;")
}
//function to display all records
function DisplayAllRows(sqlstring) // <-- can you use for any table not need to
// know column names, just use a *
// example:
{
//Use all rows what is in ExecuteSql (try any, it will works fine)
db.ExecuteSql( sqlstring, [], OnResult, OnError )
}
//Callback to show query results in debug.
function OnResult( res )
{
var len = res.rows.length;
var s = txt.GetText();
// ***********************************************************************
// This is the answer how to read column names from table:
for(var ColumnNames in res.rows.item(0)) s += " [ "+ ColumnNames +" ] "; // "[" & "]" optional, i use only in this demo
// ***********************************************************************
//app.Alert("Here is all Column names what Select from your table:\n"+s);
s+="\n";
for(var i = 0; i < len; i++ )
{
var rows = res.rows.item(i)
for (var item in rows)
{
s += " " + rows[item] + " ";
}
s+="\n\n";
}
//app.Alert(s);
txt.SetText( s )
}
//Callback to show errors.
function OnError( msg )
{
app.Alert( "Error: " + msg )
}
If you're using the SQLite3, INFORMATION_SCHEMA is not supported. Use PRAGMA table_info instead. This will return 6 rows of information about the table. To fetch the column name (row2), use a for loop like the following
cur.execute("PRAGMA table_info(table_name)") # fetches the 6 rows of data
records = cur.fetchall()
print(records)
for row in records:
print("Columns: ", row[1])
For use in Python with sqlite3
Top answer PRAGMA table_info() returns a list of tuples, which might not be suitable for further processing, e.g.:
[(0, 'id', 'INTEGER', 0, None, 0),
(1, 'name', 'TEXT', 0, None, 0),
(2, 'age', 'INTEGER', 0, None, 0),
(3, 'profession', 'TEXT', 0, None, 0)]
When using sqlite3 in Python, simply add a list comprehension in the end to filter out unwanted information.
import sqlite3 as sq
def col_names(t_name):
with sq.connect('file:{}.sqlite?mode=ro'.format(t_name),uri=True) as conn:
cursor = conn.cursor()
cursor.execute("PRAGMA table_info({}) ".format(t_name))
data = cursor.fetchall()
return [i[1] for i in data]
col_names("your_table_name")
Result
["id","name","age","profession"]
DISCLAIMER: Do not use in production as this snippet is subject to possible SQL injection!