I have a table where I'm trying to create the value of the attribute from one column based off the attribute of the value of another column...
Essentially, one column is a long series of numbers... such as 540379724021081
and I am trying to for that tuple, make another attribute value of the first 4 characters so...5403
So in the end my table would go from...
To this...
I started doing this in Python with Psycopg2...but don't think it's the right way with a quick script I made
import psycopg2
conn = psycopg2.connect("dbname='gis3capstone' user='postgres' password='password' host='localhost' port='5433'")
cur = conn.cursor()
cur.execute('SELECT * FROM fcc_form_477')
row = cur.fetchone()
while row:
val2 = str(row[0])[0:4]
# Set row[1] = val2 ??
row = cur.fetchone()
Any help to go about this?
EDIT: or SQL...if I can do it that way
You can use substr():
select substr(val1, 1, 4) as val2
If the value is a number, then convert it to a string:
select substr(val1::text, 1, 4) as val2
Related
I am currently trying to get a list of values from a table inside an SQL database. The problem is appending the values due to the table's name in which I can't change. The table's name is something like Value123/123.
I tried making a variable with the name like
x = 'Value123/123'
then doing
row.append(x)
but that just prints Value123/123 and not the values from the database
cursor = conn.cursor()
cursor.execute("select Test, Value123/123 from db")
Test = []
Value = []
Compiled_Dict = {}
for row in cursor:
Test.append(row.Test)
Value.append(row.Value123/123)
Compiled_Dict = {'Date&Time': Test}
Compiled_Dict['Value'] = Value
conn.close()
df = pd.DataFrame(Compiled_Dict)
The problem occurs in this line
Value.append(row.Value123/123)
When I run it I get that the database doens't have a table named 'Value123'. Since I think it's trying to divide 123 by 123? Unfortunately the table in the database is named like this and I cannot change it, so how do I pull the values from this table?
Edit:
cursor.execute("select Test, Value123/123 as newValue from db")
I tried this and it worked thanks for the solutions. Suggested by Yu Jiaao
Is it possible for me to take data stored in a sqlite3 table and use it as a Python variable? I'm looking for something that might be similar to this pseudo-code:
import sqlite3
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
variable = cursor.execute("fetch data from table")
To read a single value from a table, use a SELECT query that returns a result with a single row and a single column:
for row in cursor.execute("SELECT MyColumn FROM MyTable WHERE ID = ?", [123]):
variable = row[0]
break
else:
variable = 0 # not found
I have recently encountered the problem of adding the elements of a database column. Here is the following code:
import sqlite3
con = sqlite3.connect("values.db")
cur = con.cursor()
cur.execute('SELECT objects FROM data WHERE firm = "sony"')
As you can see, I connect to the database (sql) and I tell to Python to select the column "objects".
The problem is that I do not know the appropriate command for summing the selected objects.
Any ideas/ advices are highly reccomended.
Thank you in advance!!
If you can, have the database do the sum, as that reduces data transfer and lets the database do what it's good at.
cur.execute("SELECT sum(objects) FROM data WHERE firm = 'sony'")
or, if you're really just looking for the total count of objects.
cur.execute("SELECT count(objects) FROM data WHERE firm = 'sony'")
either way, your result is simply:
count = cur.fetchall()[0][0]
Try the following line:
print sum([ row[0] for row in cur.fetchall()])
If you want the items instead adding them together:
print ([ row[0] for row in cur.fetchall()])
How can be determined whether a record exists in a table? The way I tried was to do a SELECT query and then count the rows of the ResultSet using the following:
rows = session.execute("SELECT * FROM test_table WHERE id=%s", ([<id_here>]))
if len(rows) == 0:
print "Does not exist"
However, ResultSet does not support len. In another answer, they suggest to use SELECT COUNT(*) which in another reference is strongly discouraged. Is there a more standard way to do this?
You can simply do one of the following:
rows = session.execute("SELECT * FROM test_table WHERE id=%s", ([<id_here>]))
if not rows:
print "Does not exist"
Or, if selecting multiple rows you could iterate over the ResultSet with:
for row in rows:
do_something(row)
ResultSet also has a current_rows attribute which will be empty if none were returned.
See http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.ResultSet for more details on how to use the ResultSet.
Cassandra session.execute returns ResultSet object that contain current_rows attribute.
try folowing:
r = session.execute(f"SELECT * FROM test_table WHERE id = {some_id} limit 1")
if(len(r.current_rows) == 0):
# your code here
I have a tuple with a single value that's the result of a database query (it gives me the max ID # currently in the database). I need to add 1 to the value to utilize for my subsequent query to create a new profile associated with the next ID #.
Having trouble converting the tuple into an integer so that I can add 1 (tried the roundabout way here by turning the values into a string and then turning into a int). Help, please.
sql = """
SELECT id
FROM profiles
ORDER BY id DESC
LIMIT 1
"""
cursor.execute(sql)
results = cursor.fetchall()
maxID = int(','.join(str(results)))
newID = maxID + 1
If you are expecting just the one row, then use cursor.fetchone() instead of fetchall() and simply index into the one row that that method returns:
cursor.execute(sql)
row = cursor.fetchone()
newID = row[0] + 1
Rather than use an ORDER BY, you can ask the database directly for the maximum value:
sql = """SELECT MAX(id) FROM profiles"""