I am trying to connect to SQLITE database and it would seem that the code does create the database, but however it does not create the tables nor does it insert anything in them (most probably because they were never created)
I have SQLite DB Browser and in it I open the database but lack any tables or anything at all. Also I see my database in the folder next to my project.
I have the following code:
import sqlite3
conn = sqlite3.connect("dfg.db")
c = conn.cursor()
def create_tabe():
c.execute('CREATE TABLE IF NOT EXISTS tabl(city TEXT, temp REAL)')
def data_entry():
c.execute("INSERT INTO tabl VALUES ('dasfsd', 32434)")
conn.commit()
c.close()
conn.close()
Related
I am making little project with sqlite3, but table is not creating.
import sqlite3
conn = sqlite3.connect("test.sqlite")
c = conn.cursor()
c.execute('''CREATE TABLE students
(rollno real, name text, class real)''')
conn.commit()
#close the connection
conn.close()
see photo
This is not a code error.
Please navigate to where you have the python file running/saved in the DB browser. File -> Open Database and select the test.sqlite file. You will then see something like this:
Code used:
import sqlite3
conn = sqlite3.connect("test.sqlite")
c = conn.cursor()
c.execute('''CREATE TABLE students
(rollno real, name text, class real)''')
conn.commit()
#close the connection
conn.close()
I'm using the Python package MySQLdb to fetch data from a MySQL database. However, I notice that I can't fetch the entirety of the data.
import MySQLdb
db = MySQLdb.connect(host=host, user=user, passwd=password)
cur = db.cursor()
query = "SELECT count(*) FROM table"
cur.execute(query)
This returns a number less than what I get if I execute the exact same query in MySQL Workbench. I've noticed that the data it doesn't return is the data that was inserted into the database most recently. Where am I going wrong?
You are not committing the inserted rows on the other connection.
I created a database in psql and in it, created a table called "tweet".
CREATE TABLE tweet
( tid CHARACTER VARYING NOT NULL, DATA json,
CONSTRAINT tid_pkey PRIMARY KEY (tid) );
Then when I use
SELECT * FROM tweet;
in the psql window it works and shows an empty table.
Now I have a python script that takes JSON data and is loading it into this table.
conn_string = "host='localhost' port=5432 dbname='tweetsql' user='tweetsql' password='tweetsql'"
conn = psycopg2.connect(conn_string)
cur = conn.cursor()
That sets up the connection and I don't think it had any issues.
Now I have some logic to read in the JSON file and then to add it in, I say:
cur.execute("INSERT INTO tweet (tid, data) VALUES (%s, %s)", (cur_tweet['id'], json.dumps(cur_tweet, cls=DecimalEncoder), ))
But this always says that the relation tweet doesn't exist. Am I missing something here? Is there an issue with my connection or can my script somehow not see the table? For reference I'm using psycopg2 for the connection.
EDIT: I updated the DDL to include a transaction I could commit but that didn't fix it either. Is it a schema issue?
This is what I did regarding the table creation to commit:
BEGIN;
CREATE TABLE tweet
( tid CHARACTER VARYING NOT NULL, DATA json,
CONSTRAINT tid_pkey PRIMARY KEY (tid) );
COMMIT;
EDIT 2: I'm posting some code here...
import psycopg2
import json
import decimal
import os
import ctypes
conn_string = "host='localhost' port=5432 dbname='tweetsql' user='tweetsql' password='tweetsql'"
conn = psycopg2.connect(conn_string)
cur = conn.cursor()
cur.execute("CREATE TABLE tweet (tid CHARACTER VARYING NOT NULL, DATA json, CONSTRAINT tid_pkey PRIMARY KEY (tid) );")
cur.commit()
for file in os.listdir(path):
if not is_hidden(file):
with open(path+file, encoding='utf-8') as json_file:
tweets = json.load(json_file, parse_float=decimal.Decimal)
for cur_tweet in tweets:
cur.execute("INSERT INTO tweet (tid, data) VALUES (%s, %s)", (cur_tweet['id'], json.dumps(cur_tweet, cls=DecimalEncoder), ))
cur.commit()
cur.close()
conn.close()
You're probably not committing the table creation, and, (I'm assuming; not seeing your complete code) you're starting a new connection via psycopg2 each time. You need to commit right after the table creation, and not in a new connection, as each connection is its own implicit transaction. So, your code flow should be something like this:
connect to the db
create the table using the cursor
fill the table
commit and disconnect from db.
Or, if you must separate creation from filling, just commit and disconnect after (2) and then reconnect before (3).
I am able to connect Python 3.4 and Postgres but I am the query is not successfully getting executed. For e.g, the table below is not getting created
import psycopg2
from psycopg2 import connect
try:
conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost' password='postgres'")
print("Database connected!")
cur = conn.cursor()
cur.execute("""CREATE TABLE DEPARTMENT(
ID INT PRIMARY KEY NOT NULL,
DEPT CHAR(50) NOT NULL,
EMP_ID INT NOT NULL
)""")
except:
print("I am unable to connect to the database")
Just add
conn.commit()
after you've run the execute.
Relational databases have the concept of transaction, which happen (if at all) "atomically" (all-or-none). You need to commit a transaction to actually make it take place; until you've done that, you keep the option to rollback it instead, to have no changes made to the DB if you've found something iffy on the way.
I am testing Python and Mysql in that i am able to create and delete table's but i am unable to insert data in them.I searched stackoverflow and mostly they suggest to use
commit()
So i used it and even after i used the data is not inserted into the database.Please help me.
This is the code i use it creates the table but not inserting data
import MySQLdb
db = MySQLdb.connect("localhost","user","password")
cxn = MySQLdb.connect(db='test')
cursor = cxn.cursor()
cursor.execute("CREATE TABLE users(name VARCHAR(40),id VARCHAR(40))")
cursor.execute("INSERT INTO users(name,id) VALUES('John','1')")
db.commit()
print "Opertion completed successfully"
Are db and cxn connections to the same database?
You should establish your connection using following:
db = MySQLdb.connect(host="localhost",
db="test",
user="user",
passwd="password")
The cursor should then be derived from this connection via:
cursor = db.cursor()
I would hazard that your issue is coming from the ambiguity between db and cxn.