I am new in python so in the pyodbc. Maybe my question is very simple but I could not find any answer refer to my question.
I'm using this select
cursor.execute("SELECT [something] FROM [someone] WHERE [user_name]='John'")
rows = cursor.fetchall()
for row in rows:
print row.something
It prints some parameters for example 4 or 5.How to print only second or only third parameter.
I also used cursor.fetchmany() but I'm having same problem
If you wan't just the 4th row you can do:
rows = cursor.fetchall()
print rows[3].something
But it's better if you do it in the SQL query and avoid fetching all the rows from the database:
SELECT [something] FROM [someone] WHERE [user_name]='John' LIMIT 1 OFFSET 3
Example.
I guess your mean field and not parameter
cursor.execute("SELECT [something] FROM [someone] WHERE [user_name]='John'")
rows = cursor.fetchall()
from row in rows:
print row[1]
Related
I'm working on a project where I need to get data from my SQL Server, but there is a catch. In total there is around 100.000 rows in the specific column I need the data out of but I only need the last 20.000 - 30.000 rows of it.
I use the casual connection string and stored procedure but is there a way to select a specific row to start from? (for example let it start at row 70.000)
try:
CONNECTION_STRING = 'DRIVER='+driver+';SERVER='+server+';DATABASE='+databaseName+';UID='+username+';PWD='+ password
conn = pyodbc.connect(CONNECTION_STRING)
cursor = conn.cursor()
storedproc = "*"
cursor.execute(storedproc)
row = cursor.fetchone()
while row:
OID = ((int(row[1])))
print(OID)
So my question: is there a way (for example) set cursor.fetchone to row 70.000 instead of 1? Or is there another way to do that?
Thanks in advance!
I Have this example of sql database. I want to use a certain item from the database in math calculation but I can't because the value looks like this: (25.0,) instead of just 25.0. Please see the attached picture
https://imgur.com/a/j7JOZ5H
import sqlite3
#Create the database:
connection = sqlite3.connect('DataBase.db')
c = connection.cursor()
c.execute('CREATE TABLE IF NOT EXISTS table1 (name TEXT,age NUMBER)')
c.execute("INSERT INTO table1 VALUES('Jhon',25)")
#Pull out the value:
c.execute('SELECT age FROM table1')
data =c.fetchall()
print(data[0])
#simple math calculation:
r=data[0]+1
print(r)
According to Python's PEP 249, the specification for most DB-APIs including sqlite3, fetchall returns a sequence of sequences, usually list of tuples. Therefore, to retrieve the single value in first column to do arithmetic, index the return twice: for specific row and then specific position in row.
data = c.fetchall()
data[0][0]
Alternatively, fetchone returns a single row, either first or next row, in resultset, so simply index once: the position in single row.
data = c.fetchone()
data[0]
The returned data from fetchall always comes back as a list of tuples, even if the tuple only contains 1 value. Your data variable should be:
[(25,)]
You need to use:
print(data[0][0])
r = data[0][0] + 1
print(r)
Is there a better way to get the row count than doing the following?
cursor.execute("SELECT DISTINCT(provider_id) FROM main_iteminstance")
num_items = len(cursor.fetchall())
Is there a shorthand in MySQLdb for the above?
You could execute the following SQL directly on cursor.execute rather than depending on MySQLdb:
cursor.execute("SELECT COUNT(DISTINCT provider_id) FROM main_iteminstance")
Then you just get the result from that query.
The result of cursor.execute returns the number of rows returned by the query so just assign to a variable.
num_items = cursor.execute("SELECT DISTINCT(provider_id) FROM main_iteminstance")
This will also work and you won't have to run an extra query just to get the number of items
I'm able to connect with my database. But I want to change the values present in that particular column.
cursor.execute("SELECT * FROM foo;")
rows = cursor.fetchall()
for row in rows:
print(row)
Output of the above code is,
('foo,bar,foo,bar',)
('foobar,bar',)
('foo,bar,buz,buz',)
I'm able to replace the value by,
rows = cursor.fetchall()
for row in rows:
print(re.sub(r'^[^,]*,', '', row[0]))
cursor.close()
returns,
bar,foo,bar
bar
bar,buz,buz
but I don't know how to setback the altered string to that particular column.
I think i need to use update query, so I tried
for row in rows:
cursor.execute("UPDATE foo SET categories=%s;", re.sub(r'^[^,]*,', '', row[0]))
But it returns an error message of,
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1
As i said in comment you need to specify the column ID for your query :
for row in rows:
sub=re.sub(r'^[^,]*,', '', row[0])
cursor.execute("UPDATE drug_specifications SET categories=%s where id=%s;",(sub, str(row[0])))
Currently I have the following code:
c.execute("SELECT * FROM table")
for row in c.fetchall():
print row[0]
print row[1]
However, I changed the structure of my table and now I have to change the index values to represent this change. Is there a way to get use column names instead?
See Row Objects in the docs for the sqlite3 module. If you use the sqlite3.Row row_factory you'll get back an object that's slightly more powerful than the normal tuples. I imagine it has slightly higher overhead, hence not being the default behavior.
For this reason, it is recommended to always use explicit column names when doing a SELECT:
c.execute("SELECT color, fluffiness FROM table")
for row in c.fetchall():
print row[0] # <-- is always guaranteed to be the color value
print row[1]