I am new to database. I am trying to create a database and table in it.
but unable to save and open again after exiting from sqlite.
I am using sqlite3 3.6.20 on centOS, when i will enter following command
.save ex1.db or .open ex1.db
it will print following error message.
Error: unknown command or invalid arguments: "save". Enter ".help" for help
Error: unknown command or invalid arguments: "open". Enter ".help" for help
and when Print .help
it wont show any command related to save and open existing database.
thanks in advance.
I am trying to create a database and table in it. but unable to save and open again after exiting from sqlite.
You don't need to save. Each transaction writes to disk. (More or less.)
To create the database "test.sl3", you can do this. (From the command line. Programs work about the same way.)
$ sqlite3 test.sl3
SQLite version 3.8.7.2 2014-11-18 20:57:56
Enter ".help" for usage hints.
sqlite> create table test (test_id integer primary key);
sqlite> insert into test values (1);
sqlite> select * from test;
1
.quit
No .save. Now load the database again.
$ sqlite3 test.sl3
SQLite version 3.8.7.2 2014-11-18 20:57:56
Enter ".help" for usage hints.
sqlite> select * from test;
1
The data is still there.
You're supposed to provide a filename as an argument for the .save command, e.g.:
sqlite> .save ex1.db
docs: http://www.sqlite.org/cli.html
as Mike pointed out in his answer, you should provide a file name to put the database in.
If you did a lot of work and you did not provide a file name up front and you work in a version in which the .save command is not yet available (you quote that sqlite3 3.6.20 does not know it and I also do not see it in sqlite3 version 3.8.2) you can use the .backup command
sqlite> .help
[...]
.backup ?DB? FILE Backup DB (default "main") to FILE
$ sqlite3
[...]
sqlite> create table mytable ( column1 text, column2 integer );
sqlite> insert into mytable values ( 'ENTRY1', 1 );
sqlite> insert into mytable values ( 'ENTRY2', 2 );
sqlite> .backup main temp.db
sqlite> .quit
$ sqlite3 temp.db
[...]
sqlite> .schema
CREATE TABLE mytable ( column1 text, column2 integer );
sqlite> select * from mytable;
column1 column2
---------- ----------
ENTRY1 1
ENTRY2 2
Use Sqlite3 ex1.db to open your database. After that, all queries will take effect in your DB.
Maybe try using an absolute path instead of a relative path.
I am in VS Code using the SQLite extension by alexcvzz.
When I use a relative path, I get an error.
CREATE TABLE test (id INTEGER, name TEXT);
INSERT INTO test (id, name) VALUES (1, "Hello");
.save ex1.db
When I use an absolute path, it works.
CREATE TABLE test (id INTEGER, name TEXT);
INSERT INTO test (id, name) VALUES (1, "Hello");
.save /Users/zacharyargentin/databases/ex1.db
Note: In the VS Code extension you have to choose a database before you run the query, so I chose the :memory: database, which is the default in-memory database. This database deletes itself as soon as you close the connection (so if you want to keep it, you have to save it like I did in the example above).
Related
Hello I am practising and learning SQLite,
I created a SQLite file manually on VSCODE I call the file project_1.sqlite but when I try run the command
sqlite3 project_1.sqlite
i get
$ sqlite3 project_1.sqlite
SQLite version 3.36.0 2021-06-18 18:36:39
Enter ".help" for usage hints.
sqlite>
then when I say SELECT * FROM friends;
I get
sqlite> SELECT * FROM friends;
Error: file is not a database
sqlite>
I have already set up my SQLite inside the Control Pannel
Why am I getting the Error: file is not database ??
my project_1.sqlite file I already have populated it like this:
CREATE TABLE friends (
id INTEGER,
name TEXT,
birthday DATE
);
INSERT INTO friends (id, name, birthday)
VALUES (1, 'Ororo Munroe', '1940-05-30');
INSERT INTO friends (id, name, birthday)
VALUES (2, 'Sham', '1990-01-01');
INSERT INTO friends (id, name, birthday)
VALUES (3, 'Maria', '1991-01-01');
UPDATE friends
SET name = 'Storm'
WHERE id = 1;
ALTER TABLE friends
ADD COLUMN email TEXT;
UPDATE friends
SET email = 'storm#bffemail.com'
WHERE id = 1;
UPDATE friends
SET email = 'sham#bffemail.com'
WHERE id = 2;
UPDATE friends
SET email = 'maria#bffemail.com'
WHERE id = 3;
DELETE FROM friends
WHERE id = 1;
SELECT * FROM friends;
I have Windows but I have installed Bash so I am using Bash commands hope that makes sense I dont have Linux I am new to Programming as well sorry
hi I have a database which looks like this image
I have a csv which has two columns City and Main_city. I want to update Main_City against the City column from csv into database but without damaging other data into the database. How can i do this?
I do not know the logic behind it.
below are my codes:
import csv
data_obj = {}
def readfiles():
f = open("city.csv", "r")
data = f.read()
lst = data.split("\n")
for i in range(1, len(lst)):
val = lst[i].split(",")
data_obj[val[0]] = val[1]
#print(data_obj[val[0]])
print(data_obj)
readfiles()
conn = sqlite3.connect('99_data_increment.db')
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS crawled (id INTEGER PRIMARY KEY, State , XID , Project_Name , City , Main_City , Registration_Number , Promoter_Name , Rera_URL , PDF_text, Crawled_Date , Status, Names, Transaction_Date, Comments, Call_Contact_Number, Creation_Type, Builder_Website)")
New_project_db.insert(statess, XID, Projectname, City, maincity, Registration_number, promotername, rera_url, blank, fdate, "CREATED", agents_names, fdate, blank, blank, blank, blank)
## didn't getting logic behind
My csv looks like this:
If you import your CSV file with the updates into a temporary table, it's really easy to do. I want to say that pandas makes this import trivial in Python, but I'm not familiar enough to say for sure. At the very least actually using the csv library you're importing but not using would help.
Anyways, here's a way to do it from the sqlite3 shell, which is handy for a one-off update, but not good if you're trying to automate it for repeated use. Should be easy enough to adapt to python though, as the UPDATE is the important part once you've got the new data loaded into the database.
$ sqlite3 99_data_increment.db
sqlite> .mode csv
sqlite> .import updates.csv new_cities
sqlite> CREATE INDEX new_cities_idx ON new_cities(City);
sqlite> UPDATE crawled AS c
SET Main_City =
(SELECT "Main City" FROM new_cities AS n WHERE c.City = n.City)
WHERE EXISTS (SELECT * FROM new_cities AS n WHERE c.City = n.City);
sqlite> DROP TABLE new_cities;
sqlite> .quit
I'm using cqlsh to add data to Cassandra with the BATCH query and I can load the data with a query using the "-e" flag but not from a file using the "-f" flag. I think that's because the file is local and Cassandra is remote. Details below:
This is a sample of my query (there are more rows to insert, obviously):
BEGIN BATCH;
INSERT INTO keyspace.table (id, field1) VALUES ('1','value1');
INSERT INTO keyspace.table (id, field1) VALUES ('2','value2');
APPLY BATCH;
If I enter the query via the "-e" flag then it works no problem:
>cqlsh -e "BEGIN BATCH; INSERT INTO keyspace.table (id, field1) VALUES ('1','value1'); INSERT INTO keyspace.table (id, field1) VALUES ('2','value2'); APPLY BATCH;" -u username -p password -k keyspace 99.99.99.99
But if I save the query to a text file (query.cql) and call as below, I get the following output:
>cqlsh -f query.cql -u username -p password -k keyspace 99.99.99.99
Using 3 child processes
Starting copy of keyspace.table with columns ['id', 'field1'].
Processed: 0 rows; Rate: 0 rows/s; Avg. rate: 0 rows/s
0 rows imported from 0 files in 0.076 seconds (0 skipped).
Cassandra obviously accepts the command but doesn't read the file, I'm guessing that's because the Cassandra is located on a remote server and the file is located locally. The Cassandra instance I'm using is a managed service with other users, so I don't have access to it to copy files into folders.
How do I run this query on a remote instance of Cassandra where I only have CLI access?
I want to be able to use another tool to build the query.cql file and have a batch job run the command with the "-f" flag but I can't work out how I'm going wrong.
You're executing a local cqlsh client so it should be able to access your local query.cql file.
Try to remove the BEGIN BATCH and APPLY BATCH and just let the 2 INSERT statements in the query.cql and retry again.
One other solution to insert data quickly is to provide a csv file and use the COPY command inside cqlsh. Read this blog post: http://www.datastax.com/dev/blog/new-features-in-cqlsh-copy
Scripting insert by generating one cqlsh -e '...' per line is feasible but it will be horribly slow
I am trying to count the columns from a sqlite db using the sqlite command line tool. To test it I created a sample db like this:
c:\>sqlite.exe mydb.sqlite "create table tbl1(one varchar(10), two smallint);"
Now lets say i don't know that the table tbl1 has 2 columns, how can I find that using a query from the command line tool?
Run:
pragma table_info(yourTableName)
See:
http://www.sqlite.org/pragma.html#pragma_table_info
for more details.
Here is a way I found useful under Linux. Create a bash script file columns.sh and ensure it has execute permissions and copy - paste the following code.
columns() { for table in $(echo ".tables" | sqlite3 $1); do echo "$table $(echo "PRAGMA table_info($table);" | sqlite3 $1 | wc -l)"; done ;}
Type the following command, in terminal, on the first line to return results
$ columns <database name>
<table1> <# of columns>
<table2> <# of columns>
Note: Ensure database is not corrupted or encrypted.
source: http://www.quora.com/SQLite/How-can-I-count-the-number-of-columns-in-a-table-from-the-shell-in-SQLite
UPDATE
Here is an interesting URL for Python Script Solution
http://pagehalffull.wordpress.com/2012/11/14/python-script-to-count-tables-columns-and-rows-in-sqlite-database/
I have 2 SQLite databases with common data but with different purposes and I wanted to avoid reinserting data, so I was wondering if it was possible to copy a whole table from one database to another?
You'll have to attach Database X with Database Y using the ATTACH command, then run the appropriate Insert Into commands for the tables you want to transfer.
INSERT INTO X.TABLE SELECT * FROM Y.TABLE;
// "INSERT or IGNORE" if you want to ignore duplicates with same unique constraint
Or, if the columns are not matched up in order:
INSERT INTO X.TABLE(fieldname1, fieldname2) SELECT fieldname1, fieldname2 FROM Y.TABLE;
Easiest and correct way on a single line:
sqlite3 old.db ".dump mytable" | sqlite3 new.db
The primary key and the columns types will be kept.
Consider a example where I have two databases namely allmsa.db and atlanta.db. Say the database allmsa.db has tables for all msas in US and database atlanta.db is empty.
Our target is to copy the table atlanta from allmsa.db to atlanta.db.
Steps
sqlite3 atlanta.db(to go into atlanta database)
Attach allmsa.db. This can be done using the command ATTACH '/mnt/fastaccessDS/core/csv/allmsa.db' AS AM;
note that we give the entire path of the database to be attached.
check the database list using sqlite> .databases
you can see the output as
seq name file
--- --------------- ----------------------------------------------------------
0 main /mnt/fastaccessDS/core/csv/atlanta.db
2 AM /mnt/fastaccessDS/core/csv/allmsa.db
now you come to your actual target. Use the command
INSERT INTO atlanta SELECT * FROM AM.atlanta;
This should serve your purpose.
For one time action, you can use .dump and .read.
Dump the table my_table from old_db.sqlite
c:\sqlite>sqlite3.exe old_db.sqlite
sqlite> .output mytable_dump.sql
sqlite> .dump my_table
sqlite> .quit
Read the dump into the new_db.sqlite assuming the table there does not exist
c:\sqlite>sqlite3.exe new_db.sqlite
sqlite> .read mytable_dump.sql
Now you have cloned your table.
To do this for whole database, simply leave out the table name in the .dump command.
Bonus: The databases can have different encodings.
Objective-C code for copy Table from a Database to another Database
-(void) createCopyDatabase{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *maindbPath = [documentsDir stringByAppendingPathComponent:#"User.sqlite"];;
NSString *newdbPath = [documentsDir stringByAppendingPathComponent:#"User_copy.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
char *error;
if ([fileManager fileExistsAtPath:newdbPath]) {
[fileManager removeItemAtPath:newdbPath error:nil];
}
sqlite3 *database;
//open database
if (sqlite3_open([newdbPath UTF8String], &database)!=SQLITE_OK) {
NSLog(#"Error to open database");
}
NSString *attachQuery = [NSString stringWithFormat:#"ATTACH DATABASE \"%#\" AS aDB",maindbPath];
sqlite3_exec(database, [attachQuery UTF8String], NULL, NULL, &error);
if (error) {
NSLog(#"Error to Attach = %s",error);
}
//Query for copy Table
NSString *sqlString = #"CREATE TABLE Info AS SELECT * FROM aDB.Info";
sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
if (error) {
NSLog(#"Error to copy database = %s",error);
}
//Query for copy Table with Where Clause
sqlString = #"CREATE TABLE comments AS SELECT * FROM aDB.comments Where user_name = 'XYZ'";
sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
if (error) {
NSLog(#"Error to copy database = %s",error);
}
}
The Easiest way to do is through SQLite Studio
If you don't have download from https://download.cnet.com/SQLiteStudio/3000-10254_4-75836135.html
Steps:
1.Add both the databases.
2.Click View tab and then databases as shown in the picture.
3.Right click the table you want to copy and copy it.
Paste the table after right clicking the database where you want to paste.
Now you're done
First scenario: DB1.sqlite and DB2.sqlite have the same table(t1), but DB1 is more "up to date" than DB2. If it's small, drop the table from DB2 and recreate it with the data:
> DROP TABLE IF EXISTS db2.t1; CREATE TABLE db2.t1 AS SELECT * FROM db1.t1;
Second scenario: If it's a large table, you may be better off with an INSERT if not exists type solution. If you have a Unique Key column it's more straight forward, otherwise you'd need to use a combination of fields (maybe every field) and at some point it's still faster to just drop and re-create the table; it's always more straight forward (less thinking required).
THE SETUP: open SQLite without a DB which creates a temporary in memory main database, then attach DB1.sqlite and DB2.sqlite
> sqlite3
sqlite> ATTACH "DB1.sqlite" AS db1
sqlite> ATTACH "DB2.sqlite" AS db2
and use .databases to see the attached databases and their files.
sqlite> .databases
main:
db1: /db/DB1.sqlite
db2: /db/DB2.sqlite
I needed to move data from a sql server compact database to sqlite, so using sql server 2008 you can right click on the table and select 'Script Table To' and then 'Data to Inserts'. Copy the insert statements remove the 'GO' statements and it executed successfully when applied to the sqlite database using the 'DB Browser for Sqlite' app.
If you use DB Browser for SQLite, you can copy the table from one db to another in following steps:
Open two instances of the app and load the source db and target db side by side.
If the target db does not have the table, "Copy Create Statement" from the source db and then paste the sql statement in "Execute SQL" tab and run the sql to create the table.
In the source db, export the table as a CSV file.
In the target db, import the CSV file to the table with the same table name. The app will ask you do you want to import the data to the existing table, click yes. Done.