For SQL Lite why doesn't this table command work? - sqlite

So I made a table using this command
.open C:/Users/Fries/Desktop/Test.db
I closed SQL lite and populated the db with the data below using notepad
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
When I open the db and type .tables there is an error for some reason

The commands do work when used properly.
In short what you have done, is
Create and save a database that has no tables.
Open that file with Notepad (despite warnings that you may have received)
Entered some data and saved the file.
Thus deleting eveything in the file that SQLite knows about so when you open it SQLite tells you that it's not a database e.g. the first 16 bytes must be SQLite format 3\000 (see below when the database file is opened in notepad).
Open the file from within the SQLITE3 program which has then told you it's not a database.
i.e. The file that you open is the actual database not something that you have typed into notepad.
The data, which will be in columns of a table or tables. Has to be entered via SQLITE3 commands (including SQL). The CREATE TABLE... is one such SQL command (yours is valid and has been used below as it is).
What you should be doing is starting SQLIT3 (typing sqlite3 if it's path has been added to the PATH environment variable), and then entering commands such as CREATE TABLE ......
E.G.
When you first start sqlite3 from a command prompt you will get :-
C:\Users\Mike>sqlite3
SQLite version 3.22.0 2018-01-22 18:45:57
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
A database is opened as such but it is an in memory database and would be lost if you quit.
You can create an on disk database by opening it (even if it doesn't exist) using .open and then entering commands. Alternately you can enter commands and then then use the .save command afterwards to save the in-memory database to disk.
So after the above you could do :-
sqlite> .open Test.db
sqlite> CREATE TABLE Persons ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) );
sqlite> SELECT * FROM Sqlite_master;
table|Persons|Persons|3|CREATE TABLE Persons ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) )
sqlite> .quit
This creates the file Test.db (which didn't exists, otherwise it would open it)
Then creates the Persons table.
And then extracts the rows in the system table named sqlite_master (lists items including tables).
Finally it quites from SQLITE3.
Perhaps you could then do
:-
C:\Users\Mike>sqlite3 SQLite version 3.22.0 2018-01-22 18:45:57 Enter ".help" for usage hints. Connected to a transient in-memory database. Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open Test.db
sqlite> .tables Persons
sqlite> INSERT INTO Persons VALUES (1,'Smith','Fred','Somewhere','London');
sqlite> select * FROM persons; 1|Smith|Fred|Somewhere|London sqlite> .quit
Starts SQLITE3
Opens the now existing Test.db file.
Lists the tables.
inserts a row
dispslays the rows in the Persons table (i.e. the row just added)
Finally quits SQLITE3
Opening the file Test.db in notepad :-
SQLite format 3 # .°
e e ‚tablePersonsPersonsCREATE TABLE Persons ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) )
You may see some familiar data (e.g. the SQL used to create the table is stored in the sqlite_master table in the column named SQL and will be visible as is)
Other data will not be shown in a usefule/usable format.
i.e. You will find it between hard and impossible to enter the correct data to create a valid SQLite3 database file in notepad.

Related

clone a sqlite database skip some data

My application logs user access to sqlite database, the my.db file grows about 5Gb every month. There're tables like "access" which logs every user access, this table should be cleared at every beginning of the month, and it holds almost all the 5gb data. Another table "user" which holds all my users, this table should always keep its data.
So every month I need to:
ctrl+c -> ctrl+v my.db to clone a file copy(for future statistics), this is very slow for 5gb file.
clear the "access" table via "delete from access" and "vacuum", it also takes some time.
It's too slow. I wonder if there is a sql command like "export/import database structure and indices" to clone only the structure to another new.db, and then "copy * from mydb.user to newdb"
Or maybe some existing tool can do this?
Here's the sample database I'll use, representing your old database. I made a table to keep, a table to lose, and an index.
$ sqlite3 old.db
sqlite> create table KeepMe (a TEXT);
sqlite> create table DeleteMe (b TEXT);
sqlite> create index DeleteMe_b on DeleteMe(b);
sqlite> insert into KeepMe values("Hello");
sqlite> insert into DeleteMe values("World");
sqlite> .quit
First copy the schema to a new database:
$ sqlite3 old.db .schema | sqlite3 new.db
Then open the new database, ATTACH to the old database, and copy over the table(s) you want:
$ sqlite3 new.db
sqlite> attach "old.db" as old;
sqlite> insert into KeepMe select * from old.KeepMe;
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE KeepMe (a TEXT);
INSERT INTO "KeepMe" VALUES('Hello');
CREATE TABLE DeleteMe (b TEXT);
CREATE INDEX DeleteMe_b on DeleteMe(b);
COMMIT;
sqlite> .quit

Importing data from sqlite to postgres: easily convert AUTOINCREMENT

I dump my SQLite database like this:
sqlite3 database.sqlite .dump
And this is the relevant part of the dump:
CREATE TABLE auth_user(
id INTEGER PRIMARY KEY AUTOINCREMENT,
org_id INTEGER,
email CHAR(512) UNIQUE,
user_doc_id CHAR(128),
password CHAR(512),
registration_key CHAR(512),
reset_password_key CHAR(512),
registration_id CHAR(512)
);
And I have to import this to postgres. Postgres does not accept AUTOINCREMENT, but I need a similar functionality. I want to automatically process the SQLite dump in order to import it to postgres. I have read about NEXTVAL and CREATE_SEQUENCE, but I can not automate the conversion using that easily
Is there a simple way of sedding the sqlite dump to feed it to postgres?
Replace INTEGER PRIMARY KEY AUTOINCREMENT with SERIAL PRIMARY KEY.
Ensure to catch all ways to write it (lowercase, whitespace etc.).

Opening database file from within SQLite command-line shell

I'm using the SQLite Command Line Shell. As documented, I can open a database by supplying it as an argument to the executable:
sqlite3 data.db
I cannot figure out how to open a database file from within the tool after having invoked it without supplying the file as a command-line argument (if I, say, double-click sqlite3.exe in Windows).
What is the command within the SQLite shell tool to specify a database file?
You can attach one and even more databases and work with it in the same way like using sqlite dbname.db
sqlite3
:
sqlite> attach "mydb.sqlite" as db1;
and u can see all attached databases with
.databases
where in normal way the main is used for the command-line db
.databases
seq name file
--- --------------- ----------------------------------------------------------
0 main
1 temp
2 ttt c:\home\user\gg.ite
I think the simplest way to just open a single database and start querying is:
sqlite> .open "test.db"
sqlite> SELECT * FROM table_name ... ;
Notice: This works only for versions 3.8.2+
The command within the Sqlite shell to open a database is .open
The syntax is,
sqlite> .open dbasename.db
If it is a new database that you would like to create and open, it is
sqlite> .open --new dbasename.db
If the database is existing in a different folder, the path has to be mentioned like this:
sqlite> .open D:/MainFolder/SubFolder/...database.db
In Windows Command shell, you should use '\' to represent a directory, but in SQLite directories are represented by '/'.
If you still prefer to use the Windows notation, you should use an escape sequence for every '\'
The same way you do it in other db system, you can use the name of the db for identifying double named tables. unique tablenames can used directly.
select * from ttt.table_name;
or if table name in all attached databases is unique
select * from my_unique_table_name;
But I think the of of sqlite-shell is only for manual lookup or manual data manipulation and therefor this way is more inconsequential
normally you would use sqlite-command-line in a script
You can simply specify the database file name in the command line:
bash-3.2 # sqlite3 UserDb.sqlite
SQLite version 3.16.2 2017-01-06 16:32:41
Enter ".help" for usage hints.
sqlite> .databases
main: /db/UserDb.sqlite
sqlite> .tables
accountLevelSettings genres syncedThumbs
collectionActivity recordingFilter thumbs
contentStatus syncedContentStatus
sqlite> select count(*) from genres;
10
Moreover, you can execute your query from the command line:
bash-3.2 # sqlite3 UserDb.sqlite 'select count(*) from genres'
10
You could attach another database file from the SQLite shell:
sqlite> attach database 'RelDb.sqlite' as RelDb;
sqlite> .databases
main: /db/UserDb.sqlite
RelDb: /db/RelDb_1.sqlite
sqlite> .tables
RelDb.collectionRelationship contentStatus
RelDb.contentRelationship genres
RelDb.leagueRelationship recordingFilter
RelDb.localizedString syncedContentStatus
accountLevelSettings syncedThumbs
collectionActivity thumbs
The tables from this 2nd database will be accessible via prefix of the database:
sqlite> select count(*) from RelDb.localizedString;
2442
But who knows how to specify multiple database files from the command line to execute the query from the command line?
create different db files using
>sqlite3 test1.db
sqlite> create table test1 (name text);
sqlite> insert into test1 values('sourav');
sqlite>.exit
>sqlite3 test2.db
sqlite> create table test2 (eid integer);
sqlite> insert into test2 values (6);
sqlite>.exit
>sqlite
SQLite version 3.8.5 2014-06-04 14:06:34
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open test1.db
sqlite> select * from test1;
sourav
sqlite> .open test2.db
sqlite> select * from test1;
Error: no such table: test1
sqlite> select * from test2;
6
sqlite> .exit
>
Thank YOU.
Older SQLite command-line shells (sqlite3.exe) do not appear to offer the .open command or any readily identifiable alternative.
Although I found no definitive reference it seems that the .open command was introduced around version 3.15. The SQLite Release History first mentions the .open command with 2016-10-14 (3.15.0).
I wonder why no one was able to get what the question actually asked. It stated What is the command within the SQLite shell tool to specify a database file?
A sqlite db is on my hard disk E:\ABCD\efg\mydb.db. How do I access it with sqlite3 command line interface? .open E:\ABCD\efg\mydb.db does not work. This is what question asked.
I found the best way to do the work is
copy-paste all your db files in 1 directory (say E:\ABCD\efg\mydbs)
switch to that directory in your command line
now open sqlite3 and then .open mydb.db
This way you can do the join operation on different tables belonging to different databases as well.
In my case, I wanted to open a database from another drive by providing the path as a parameter, but it wasn't working. The solution is to wrap the full path to the db in double quotes. So from Powershell window in the folder containing your sqlite3.exe:
.\sqlite3.exe "E:\ABCD\efg\mydb.db"

Please help me With my SQLITE 2 problem:(

How can i edit .sqlite file ? Can we convert it to convert to readable text format ?
Here is file link.. http://FastFreeFileHosting.com/file/52328/uploads-sqlite.html
You need the SQLite 2.x command line shell for your operating system to manipulate your uploads.sqlite file.
You can use it to get a full database dump as an SQL transaction:
$ sqlite uploads.sqlite .dump
BEGIN TRANSACTION;
CREATE TABLE 'temp' (
hash text,
file_id integer,
file_name text,
user_info text,
date integer
);
INSERT INTO temp VALUES('248283734d02fac7197b02b3cea7b25c',1,'blocklist.xml','199.27.128.60',20101207124952);
.
.
.
INSERT INTO temp VALUES('10f50e1f9266180306153b900233bdcd',20,'Joku.sis','175.40.26.96',20110103015449);
CREATE TABLE 'uploads' (
id integer(32) not null primary key unique,
filename text(100),
date integer,
user_info text,
hash text
);
INSERT INTO uploads VALUES(1,'blocklist.xml',20101207124943,'199.27.128.60','82d69cf46c45760176f7b214a5cf36b1');
.
.
.
INSERT INTO uploads VALUES(20,'Joku.sis',20110103015402,'175.40.26.96','43a61da540a8e97fedb180c8984a4d3b');
COMMIT;
You can also perform specific queries or updates using SQL:
$ sqlite uploads.sqlite
SQLite version 2.8.17
Enter ".help" for instructions
sqlite> INSERT INTO uploads VALUES(21,'Joku.sis2',20110102015402,'175.40.26.97','43a61da540a8e97fedb180c8984a4d3b');
sqlite> SELECT * FROM uploads WHERE date > 20101224000000;
19|tab-view.zip|20101230002321|27.97.29.98|5a9e7ff82c5a424fe5a19d97079b6dc7
20|Joku.sis|20110103015402|175.40.26.96|43a61da540a8e97fedb180c8984a4d3b
21|Joku.sis2|20110102015402|175.40.26.97|43a61da540a8e97fedb180c8984a4d3b
sqlite>
you could use a shell script to create an HTML or CSV file of the contents of the SQLite database. Will work in any OS (in windows, you will need to install some additional tools).
See Using sqlite3 in a shell script from Command Line Shell For SQLite from the SQLite website. Or you could use a GUI tool.

How can one see the structure of a table in SQLite? [duplicate]

This question already has answers here:
Is there an SQLite equivalent to MySQL's DESCRIBE [table]?
(7 answers)
Closed 7 years ago.
How can I see the structure of table in SQLite as desc was in Oracle?
PRAGMA table_info(table_name);
This will work for both: command-line and when executed against a connected database.
A link for more details and example. thanks
SQLite Pragma Command
Invoke the sqlite3 utility on the database file, and use its special dot commands:
.tables will list tables
.schema [tablename] will show the CREATE statement(s) for a table or tables
There are many other useful builtin dot commands -- see the documentation at http://www.sqlite.org/sqlite.html, section Special commands to sqlite3.
Example:
sqlite> entropy:~/Library/Mail>sqlite3 Envelope\ Index
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
addresses ews_folders subjects
alarms feeds threads
associations mailboxes todo_notes
attachments messages todos
calendars properties todos_deleted_log
events recipients todos_server_snapshot
sqlite> .schema alarms
CREATE TABLE alarms (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, alarm_id,
todo INTEGER, flags INTEGER, offset_days INTEGER,
reminder_date INTEGER, time INTEGER, argument,
unrecognized_data BLOB);
CREATE INDEX alarm_id_index ON alarms(alarm_id);
CREATE INDEX alarm_todo_index ON alarms(todo);
Note also that SQLite saves the schema and all information about tables in the database itself, in a magic table named sqlite_master, and it's also possible to execute normal SQL queries against that table. For example, the documentation link above shows how to derive the behavior of the .schema and .tables commands, using normal SQL commands (see section: Querying the database schema).
You can query sqlite_master
SELECT sql FROM sqlite_master WHERE name='foo';
which will return a create table SQL statement, for example:
$ sqlite3 mydb.sqlite
sqlite> create table foo (id int primary key, name varchar(10));
sqlite> select sql from sqlite_master where name='foo';
CREATE TABLE foo (id int primary key, name varchar(10))
sqlite> .schema foo
CREATE TABLE foo (id int primary key, name varchar(10));
sqlite> pragma table_info(foo)
0|id|int|0||1
1|name|varchar(10)|0||0
You should be able to see the schema by running
.schema <table>
.schema TableName
Where TableName is the name of the Table
You will get the structure by typing the command:
.schema <tableName>
If you are using PHP you can get it this way:
<?php
$dbname = 'base.db';
$db = new SQLite3($dbname);
$sturturequery = $db->query("SELECT sql FROM sqlite_master WHERE name='foo'");
$table = $sturturequery->fetchArray();
echo '<pre>' . $table['sql'] . '</pre>';
$db->close();
?>
You can use the Firefox add-on called SQLite Manager to view the database's structure clearly.

Resources