How to get table names using sqlite3 through python? [duplicate] - python

This question already has answers here:
List of tables, db schema, dump etc using the Python sqlite3 API
(12 answers)
Closed 7 years ago.
I have a problem to get data from the sqlite3 database. I can't find out the names of tables and their encoding. When I open DB through sqlitebrowser names were just unreadable characters.
Connection to DB is fine.
conn = sqlite3.connect('my.db')
conn_cursor = conn.cursor()
conn.text_factory = str
But how can I get the names of tables and their encoding?

You can use this query to get tables names.
res = conn.execute("SELECT name FROM sqlite_master WHERE type='table';")
for name in res.fetchall():
print(name[0])

Related

My data doesn't show up on DB Browser for SQLite [duplicate]

This question already has answers here:
Sqlite insert query not working with python?
(2 answers)
Closed 1 year ago.
I am currently learning SQL for one of my projects and the site, that I learn from, advised me to use DB Browser to see my Database Content. However, I can't see the data inside the SQL. This is how my code looks like. I'm creating a table and then trying to write some values in it. It creates the DB successfully but the data doesn't show up.
import sqlite3 as sql
connection = sql.connect("points.db")
cursor = connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS servers (server_id TEXT, name TEXT, exp INTEGER)")
cursor.execute("INSERT INTO servers VALUES ('848117357214040104', 'brknarsy', 20)")
Can you check that your data is inserted?
Something like this in the end:
cursor.execute("SELECT * FROM servers")
r = cursor.fetchall()
for i in r:
print(r)
Perhaps SQLite browser just needs a refresh

Best way to access schema in postgres with sqlalchemy [duplicate]

This question already has answers here:
SQLAlchemy support of Postgres Schemas
(12 answers)
SQLAlchemy: engine, connection and session difference
(3 answers)
Closed 5 years ago.
I am working with a Postgres database. This database has three schemas (schema_1, schema_2, public). If I run a simple query, the public schema will be queried by default:
from sqlalchemy import create_engine
con = create_engine('postgresql+pg8000://usr:pwd#server/db')
con.execute('select count(*) from the_table')
I cannot access the tables in schema_1 or schema_2, unless I specify the path in the query:
con.execute('select count(*) from schema_1.the_table')
Is there any way to specify the default path of the query to schema_1 without the need of specifying the full path in the query itself?
I tried with:
con.execute('SET search_path TO "schema_1";')
but this does not seem to work:
insp = inspect(con)
print(insp.default_schema_name)
# 'public'
I believe I am not executing the SET search_path TO "schema_1" correctly because the same command does work in other Postgres clients (like pgAdmin)

Using a function to get column names Sqlite3 [duplicate]

This question already has answers here:
Is there a way to get a list of column names in sqlite?
(13 answers)
Closed 6 years ago.
I have a short question for one of my classes; it involves building a function in python that takes a sqlite database name and a table name as arguments, and returns the column names inside this table.
So far I have done the following:
#!/user/bin/env python
import sqlite3
import pprint
pp = pprint.PrettyPrinter()
def print_table_columns(database_name, table_name):
conn = sqlite3.connect(database_name)
c = conn.cursor()
c.execute('SELECT sql FROM sqlite_master WHERE type=\'table\' AND name=\'table_name\'')
print c.fetchall()
conn.close()
Sadly, this code produces an empty list. I suspect that the SQL command inside the execute function does not take variables defined in Python, but I am not sure. Any help on this would be much appreciated.
Sure, you need to parameterize the query:
c.execute("""
SELECT
sql
FROM
sqlite_master
WHERE
type = 'table' AND
name = ?""", (table_name, ))
where ? is a placeholder that sqlite3 would fill with the query parameter (table_name here).

How to insert values in mysql from loop in Python [duplicate]

This question already has answers here:
Database does not update automatically with MySQL and Python
(6 answers)
Closed 7 years ago.
In MySQL I have create db with name "test" and one table with name "table". Table have one column name: "A" and set as datatype INT(1).
In Python I have this code:
import MySQLdb
db = MySQLdb.connect(host="localhost",
user="root",
db="test")
cur = db.cursor()
myList = [1,2,3,4]
for row in myList:
print row
cur.execute("INSERT INTO table (a) VALUES (%s)" % row)
Goal from code above is after loop is finish my table "table" shoud have data like this:
|A|
|1|
|2|
|3|
|4|
But my table is empty after refresing. So my question is how to insert into table from loop in Python
Tnx
You did not commit your transaction. Try adding db.commit() after the loop.
You can use db.commit () after your data is loaded or set db.autocommit(True) beforehand.

In what way can I know the tables in a .db file using Python SQLite3? [duplicate]

This question already has answers here:
List of tables, db schema, dump etc using the Python sqlite3 API
(12 answers)
Closed 8 years ago.
here's the code:
import sqlite3
cx = sqlite3.connect("test.db")
cu = cx.cursor()
# create table 1.
cu.execute("create table user_info1 (user_id text primary key,followers integer, asks integer, answers integer, goods integer)")
# create table 2
cu.execute("create table user_info2 (user_id text primary key,followers integer, asks integer, answers integer, goods integer)")
Now I'm wondering to see how many tables are in test.db:
cu.execute('.tables') # doesn't work.
cu.execute('select * from test.sqlite_master where type = "table"')
# OperationalError: no such table: test.sqlite_master
The methods above doesn't work for me. Have any hint? Thanks!
The name of your database is not test (that would be part of the file name) but main:
cu.execute("SELECT * FROM main.sqlite_master WHERE type = 'table'")
And main is the default database name, so you do not even need to specifiy it:
cu.execute("SELECT * FROM sqlite_master WHERE type = 'table'")

Categories

Resources