Display all the tables in the current database using SQLite [duplicate] - c#

What SQL can be used to list the tables, and the rows within those tables in an SQLite database file - once I have attached it with the ATTACH command on the SQLite 3 command line tool?

There are a few steps to see the tables in an SQLite database:
List the tables in your database:
.tables
List how the table looks:
.schema tablename
Print the entire table:
SELECT * FROM tablename;
List all of the available SQLite prompt commands:
.help

The .tables, and .schema "helper" functions don't look into ATTACHed databases: they just query the SQLITE_MASTER table for the "main" database. Consequently, if you used
ATTACH some_file.db AS my_db;
then you need to do
SELECT name FROM my_db.sqlite_master WHERE type='table';
Note that temporary tables don't show up with .tables either: you have to list sqlite_temp_master for that:
SELECT name FROM sqlite_temp_master WHERE type='table';

It appears you need to go through the sqlite_master table, like this:
SELECT * FROM dbname.sqlite_master WHERE type='table';
And then manually go through each table with a SELECT or similar to look at the rows.
The .DUMP and .SCHEMA commands doesn't appear to see the database at all.

To show all tables, use
SELECT name FROM sqlite_master WHERE type = "table"
To show all rows, I guess you can iterate through all tables and just do a SELECT * on each one. But maybe a DUMP is what you're after?

Use .help to check for available commands.
.table
This command would show all tables under your current database.

There is a command available for this on the SQLite command line:
.tables ?PATTERN? List names of tables matching a LIKE pattern
Which converts to the following SQL:
SELECT name FROM sqlite_master
WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'
UNION ALL
SELECT name FROM sqlite_temp_master
WHERE type IN ('table','view')
ORDER BY 1

To list the tables you can also do:
SELECT name FROM sqlite_master
WHERE type='table';

I use this query to get it:
SELECT name FROM sqlite_master WHERE type='table'
And to use in iOS:
NSString *aStrQuery=[NSString stringWithFormat:#"SELECT name FROM sqlite_master WHERE type='table'"];

Try PRAGMA table_info(table-name);
http://www.sqlite.org/pragma.html#schema

According to the documentation, the equivalent of MySQL's SHOW TABLES; is:
The ".tables" command is similar to setting list mode then executing
the following query:
SELECT name FROM sqlite_master
WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'
UNION ALL
SELECT name FROM sqlite_temp_master
WHERE type IN ('table','view')
ORDER BY 1;
However, if you are checking if a single table exists (or to get its details), see LuizGeron's answer.

As of the latest versions of SQLite 3 you can issue:
.fullschema
to see all of your create statements.

The easiest way to do this is to open the database directly and use the .dump command, rather than attaching it after invoking the SQLite 3 shell tool.
So... (assume your OS command line prompt is $) instead of $sqlite3:
sqlite3> ATTACH database.sqlite as "attached"
From your OS command line, open the database directly:
$sqlite3 database.sqlite
sqlite3> .dump

Via a union all, combine all tables into one list.
select name
from sqlite_master
where type='table'
union all
select name
from sqlite_temp_master
where type='table'

Use:
import sqlite3
TABLE_LIST_QUERY = "SELECT * FROM sqlite_master where type='table'"

Use .da to see all databases - one is called 'main'.
Tables of this database can be seen by:
SELECT distinct tbl_name from sqlite_master order by 1;
The attached databases need prefixes you chose with AS in the statement ATTACH, e.g., aa (, bb, cc...) so:
SELECT distinct tbl_name from **aa.sqlite_master** order by 1;
Note that here you get the views as well. To exclude these add:
where type = 'table'
before ' order'

Since nobody has mentioned about the official reference of SQLite, I think it may be useful to refer to it under this heading:
https://www.sqlite.org/cli.html
You can manipulate your database using the commands described in this link. Besides, if you are using Windows OS and do not know where the command shell is, that is in the SQLite's site:
https://www.sqlite.org/download.html
After downloading it, click sqlite3.exe file to initialize the SQLite command shell. When it is initialized, by default this SQLite session is using an in-memory database, not a file on disk, and so all changes will be lost when the session exits. To use a persistent disk file as the database, enter the ".open ex1.db" command immediately after the terminal window starts up.
The example above causes the database file named "ex1.db" to be opened and used, and created if it does not previously exist. You might want to use a full pathname to ensure that the file is in the directory that you think it is in. Use forward-slashes as the directory separator character. In other words use "c:/work/ex1.db", not "c:\work\ex1.db".
To see all tables in the database you have previously chosen, type the command .tables as it is said in the above link.
If you work in Windows, I think it might be useful to move this sqlite.exe file to same folder with the other Python files. In this way, the Python file writes to and the SQLite shell reads from .db files are in the same path.

The ".schema" commando will list available tables and their rows, by showing you the statement used to create said tables:
sqlite> create table_a (id int, a int, b int);
sqlite> .schema table_a
CREATE TABLE table_a (id int, a int, b int);

Related

How to iterate and export all tables in a SQL Server database?

Our tests traces are written into a SQL Server database such that every test gets it's own table: log_table_<test_name>.
All the traces are written into the same database.
Is there anyway to iterate over all the tables and export each of them to file via C#?
Just fire a query over tables and you will get all tables that match your test table name format:
select *
from information_schema.tables
where table_name like 'log_table_%'
Another option is to use sys.all_objects:
select *
from sys.all_objects
where type = 'U'
and name like 'log_table_%'
You can check the columns returned in the data set, or check the information_schema.columns or sys.all_columns view for the column names.
You can use the SqlConnection.GetSchema method to retrieve all the tables such as the following
sqlConnection.Open();
DataTable tables = sqlConnection.GetSchema("Tables");
sqlConnection.Close();
kindly note that the returned data table contains both tables and views however there is a column table_type, which tells you whether it's a VIEW or a BASE TABLE.

The schema returned by the new query differs from the base query (C#/SQL - VS 2012)

For a homework task I have to develop a C# application to interface with a SQL Server database file (.mdf), providing a dataGridView to browse the contents, and several buttons to execute queries.
I have been going well, found how to add queries to my table adapter, how to call them etc.
Now I am having problems making a query that returns the maximum pay in hourlyPayRate.
I have a database employee that contains the following attributes: employeeID, name, position, hourlyPayRate.
My query is
SELECT MAX(hourlyPayRate)
FROM employee
I right click employeeTableAdapter, click "Add Query...", name it Max and put in the query. When I click okay I get the following error message:
The schema returned by the new query differs from the base query.
The query executes correctly in the query builder, it is only when I click "OK" to save it that I receive the error.
Looking around SE there are no definitive answers to this question.
Thanks, Michael.
The solution has been found, for all those wondering.
The problem is that the query returns a table which has a different number of columns that the database.
Usually in most DBMS's this is not an issue, but for some reason Visual Studio was having none of that.
The solution was this query:
SELECT employeeID, name, position, hourlyPayRate
FROM employee
WHERE (hourlyPayRate =
(SELECT MAX(hourlyPayRate) AS MaxRate
FROM employee AS TempTable))
And then trimming the unneeded from the result as you like. For me this was as simple as having a label that derived it's data only from the hourlyPayRate attribute.
The actual reason for this is that the base QUERY returns more or less columns than the QUERY you are adding . Visual Studio cares about this ; and should not after all it is a new query.
NOTE: We are talking query columns not Database Table Columns. The Error regards Base Query - for example a fill, and perhaps you want to have a fill by and hide the field of a foreignID - because your base query outputs that column, and your added query does not - the new query differs from the base in that the columns are not the same. (I think this is done to ensure bound objects are properly bound; but I really do not know (think datagridview.)
So for example
Fill() Query
SELECT Id, Name, FKtblThing_ID
FROM ITEMS
Adding this query works..
FillByID() Query
SELECT Id, Name, FKtblThing_ID
FROM ITEMS
WHERE (FKtblThing_ID = #FKtbl_ThingID)
If instead you tried this - it would not work.
FillByID() Query
SELECT Id, Name
FROM ITEMS
WHERE (FKtblThing_ID = #FKtbl_ThingID)
This is the error you would receive:
The schema returned by the new query differs from the base query.
Everyone is wrong here, you don't edit the sql in the table adapter but edit the sql in the dataset.

SQLite Attach command and Linq to SQL

If you open a sqlite-database from a file you can later attach another file an give it a name, in case it contains equally named tables as the first database.
Using DataContext.GetTable() will return the table of type T from the "original" database. Is there a way to get the other table as well?
How would you do something like "INSERT INTO Person SELECT * FROM Source.Person" in linq, if "Source" is the database you attached?

how can i check whether a table exists in the database (ACCESS or SQL) in C#

I found a lot of questions regarding with this question.
But is there any simple statements to accomplish this task?
for both SQL and ACCESS
IF (EXISTS (SELECT 1 FROM sys.tables WHERE name = 'table_name'))
BEGIN
-- do stuff
END
sys.tables can also give you some information about the table object, e.g. the is_replicated column tells you if the table was created by replication or the has_replication_filter column tells you if the table has a replication filter set up
NB: this is for SQL Server
Edit:
For Access:
SELECT COUNT(*) as Exists from MsysObjects
WHERE type = 1
AND name = 'MY_TABLE_NAME'
Note that there is no standardized way to do this in SQL, you will have to write plattform-specific code.
To my knowledge, all DBMS have this functionality in one way or another, but it differs greatly, eg in Oracle you can query the sys.all_tables view.
You can also do using OBJECT_ID.
IF OBJECT_ID('table1') IS NOT NULL
print 'Exists'
else
print 'Not Exists'

How do I add a record only if it doesn't already exist in SQL Server?

I have a project in C# with a Sql-server Database.
In that database I have a table named 'Process' and columns named 'process_name', 'Full_Name' and 'Version' (all of the type:nvarchar(50)).
I want to write a query wich will add the new process, only if it doesn't exist in the table yet.
How can I do that?
Many thanks,
IF NOT EXISTS (SELECT * FROM Process WHERE process_name = 'xxx')
INSERT INTO Process (process_name, Full_Name, Version)
VALUES ('xxx', 'yyy', 'zzz')
You might be interested in the MERGE command which is new to SQL Server 2008.
http://technet.microsoft.com/en-us/library/bb510625.aspx
This allows you to insert rows that don't exist or update records that do exist all in one statement.
Assuming process_name is the PK that you want to check on:
IF NOT EXISTS(SELECT 1 FROM Process WHERE process_name = #ProcessName)
BEGIN
-- Process does not already exist, so INSERT
END

Categories

Resources