I have two dataframes.
One is music.
name
Date
Edition
Song_ID
Singer_ID
LA
01.05.2009
1
1
1
Second
13.07.2009
1
2
2
Mexico
13.07.2009
1
3
1
Let's go
13.09.2009
1
4
3
Hello
18.09.2009
1
5
(4,5)
And another dataframe called singer
Singer
nationality
Singer_ID
JT Watson
USA
1
Rafinha
Brazil
2
Juan Casa
Spain
3
Kidi
USA
4
Dede
USA
5
Now I would like to create a database called musicten from these two dataframes using sqlite3.
What I done so far:
import sqlite3
conn = sqlite3.connect('musicten.db')
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS singer
([Singer_ID] INTEGER PRIMARY KEY, [Singer] TEXT, [nationality] TEXT)
''')
c.execute('''
CREATE TABLE IF NOT EXISTS music
([SONG_ID] INTEGER PRIMARY KEY, [SINGER_ID] INTEGER SECONDARY KEY, [name] TEXT, [Date] DATE, [EDITION] INTEGER)
''')
conn.commit()
import sqlite3
conn = sqlite3.connect('musicten.db')
c = conn.cursor()
c.execute('''
INSERT INTO singer (Singer_ID, Singer,nationality)
VALUES
(1,'JT Watson',' USA'),
(2,'Rafinha','Brazil'),
(3,'Juan Casa','Spain'),
(4,'Kidi','USA'),
(5,'Dede','USA')
''')
c.execute('''
INSERT INTO music (Song_ID,Singer_ID, name, Date,Edition)
VALUES
(1,1,'LA',01/05/2009,1),
(2,2,'Second',13/07/2009,1),
(3,1,'Mexico',13/07/2009,1),
(4,3,'Let's go',13/09/2009,1),
(5,tuple([4,5]),'Hello',18/09/2009,1)
''')
conn.commit()
But this code seems not work to insert values to the dataframe.
SO my goal is to INSERT VALUES to the Table that the database has two tables with values.
First, do not import sqlite3 the second time. Also, you still have an open connection.
Two issues with the SQL:
'Let''s go' (single quote character must be doubled/escaped
tuple([4,5]) => '(4,5)'
I am learning python and trying to replicate what online tutorials do. I am trying to create a python desktop app where data is store in Postgresql. code is added below,
`cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)")`
problem is with (id INTEGER PRIMARY KEY), when i execute the code its showing none in place of 1st index. i want to show numbers.
please help
this is for Python 3.7.3, psycopg2==2.8.3,
def connect():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY,
title text, author text, year integer, isbn integer)")
conn.commit()
conn.close()
the result I am expecting is auto increment of numbers in 1st index where as presently it shows NONE.
below is the present and expected result again.
none title auther year isbn
01 title auther year isbn
Trying to use a Cursor execute will not work for a CREATE statement and hence the NONE. See below for an example.
Re Indexes :-
There will be no specific index as column_name INTEGER PRIMARY KEY is special in that it defines the column as an alias of the rowid column which is a special intrinsic index using the underlying B-tree storage engine.
When a row is inserted then if no value is specified for the column (e.g. INSERT INTO book (title,author, year, isbn) VALUES ('book1','The Author','1999','1234567890') then id will be 1 and typically (but not certainly) the next row inserted will have an id of 2 and so on.
If after adding some rows you use SELECT * FROM book, then the rows will be ordered according to the id as no other index is specified/used.
Perhaps have a look at Rowid Tables.
Example
Perhaps consider the following example :-
DROP TABLE IF EXISTS book;
CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer);
INSERT INTO book (title,author, year, isbn) VALUES
('book1','The Author','1999','1234567890'),
('book2','Author 2','1899','2234567890'),
('book3','Author 3','1799','3234567890')
;
INSERT INTO book VALUES (100,'book10','Author 10','1999','4234567890'); --<<<<<<<<<< specific ID
INSERT INTO book (title,author, year, isbn) VALUES
('book11','Author 11','1999','1234567890'),
('book12','Author 12','1899','2234567890'),
('book13','Author 13','1799','3234567890')
;
INSERT INTO book VALUES (10,'book10','Author 10','1999','4234567890'); --<<<<<<<<<< specific ID
SELECT * FROM book;
This :-
DROPs the book table (to make it easily re-runable)
CREATEs the book table.
INSERTs 3 books with the id not specified (typpical)
INSERTs a fourth book but with a specific id of 100
INSERTs another 3 books (not that these will be 101-103 as 100 is the highest id before the inserts)
INSERTs a last row BUT with a specific id of 10.
SELECTs all rows with all columns from the book table ordered, as no ORDER BY has been specified, according to the hidden index based upon the id. NOTE although id 10 was the last inserted it is the 4th row.
Result
In Python :-
conn = sqlite3.connect("books.db")
conn.execute("DROP TABLE IF EXISTS book")
conn.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY,title text, author text, year integer, isbn integer)")
conn.execute("INSERT INTO book (title,author, year, isbn) "
"VALUES('book1','The Author','1999','1234567890'), "
"('book2','Author 2','1899','2234567890'), "
"('book3','Author 3','1799','3234567890');")
conn.execute("INSERT INTO book VALUES (100,'book10','Author 10','1999','4234567890'); --<<<<<<<<<< specific ID")
conn.execute("INSERT INTO book (title,author, year, isbn) VALUES ('book11','Author 11','1999','1234567890'),('book12','Author 12','1899','2234567890'),('book13','Author 13','1799','3234567890');")
conn.execute("INSERT INTO book VALUES (10,'book10','Author 10','1999','4234567890'); --<<<<<<<<<< specific ID")
cur = conn.cursor()
cur.execute("SELECT * FROM book")
for each in cur:
print("{0:<20} {1:<20} {2:<20} {3:<20} {4:<20}".format(each[0],each[1],each[2],each[3],each[4]))
conn.commit()
conn.close()
The results in :-
1 book1 The Author 1999 1234567890
2 book2 Author 2 1899 2234567890
3 book3 Author 3 1799 3234567890
10 book10 Author 10 1999 4234567890
100 book10 Author 10 1999 4234567890
101 book11 Author 11 1999 1234567890
102 book12 Author 12 1899 2234567890
103 book13 Author 13 1799 3234567890
because you say I am inserting the data manually then instead of
def connect():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY,
title text, author text, year integer, isbn integer)")
conn.commit()
conn.close()
Try to use
def connect():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("SELECT * FROM books")
for row in cur:
print(row[0],row[1],row[2],row[3],row[4])
conn.commit()
conn.close()
I am moving data from one database to another with the following statment
cursor.execute("\
INSERT INTO table (ID, Country)\
SELECT ID, Country\
FROM database.t\
WHERE Country = `USA`\
GROUP BY Country\
;")
But I get the error
sqlite3.OperationalError: no such column: USA
Can't figure out why
Use single quotes, not backticks, when referring to a string literal in your SQLite query:
INSERT INTO table (ID, Country)
SELECT ID, Country
FROM database.t
WHERE Country = 'USA'
GROUP BY Country
Hello, I connected two MySql tables with foreign key and I want to insert data into them through python. here is the piece of code that works but there should be an alternative and professional way to do so otherwise I don't need foreign key and I just insert ID of first table customer_id column of the second table. thanks for helping.
Product = str(self.Text.GetValue())
Product2 = str(self.Description.GetValue())
db=MySQLdb.connect('127.0.0.1', 'root','password', 'database')
cursor = db.cursor()
cursor.execute("INSERT INTO customer (Address) VALUES (%s)", (Product))
cursor.execute("SELECT id FROM customer ORDER BY id DESC LIMIT 1")
rows = cursor.fetchall()
the_id= rows[0][0]
cursor.execute("INSERT INTO product_order (customer_id, description) VALUES (%s,%s)", (the_id,Product2))
cursor.execute("commit")
use db.insert_id() to get the last inserted id/customer_id
Err... the_id = cursor.lastrowid.
I'm trying to find a way to select a row in sqlite from Python. Say I have a table soft drinks with columns drink and price, with the primary key being drink name. I want to select coke out of drink name. How would I do this without looping through every single entry?
Here's my code:
conn = sqlite3.Connection("database.db")
curs = conn.cursor()
curs.execute("create table soft drinks (drink name TEXT, drink TEXT, price INTEGER)"
curs.execute("insert into soft drinks (drink name, drink, price) values ("coke", "whatever", 89)")
I'm looking for a command something like curs.execute(select "coke" from soft drinks) and it will return the whole row.
SQLite uses quotation marks as column identifiers, so you'd need to put quotation marks around the column and table name: SELECT * FROM "soft drinks" WHERE "drink name" = 'Coke';