Home > Back-end >  How get data where they similar to a tuple?
How get data where they similar to a tuple?

Time:07-07

I want select data from a table that similar to a tuple. I mean get just data that like in my tuple for example t1

conn = sqlite3.connect('mydatabase.db')
cur = conn.cursor()
result = cur.execute("SELECT Sum(amount) FROM items WHERE id In 't1' ")
c1 = cur.fetchall()

But I get this error: sqlite3.OperationalError: no such table: t1

CodePudding user response:

You need to select a column from the table.

SELECT Sum(amount) From items Where Id In (Select Col1 from TableName)

If you want to get values that match multiple columns, then the inner select should union those columns.

SELECT Sum(amount) From items Where Id In (Select Col1 from TableName Union Select Col2 from TableName)

CodePudding user response:

When you get data from an SQL database, you must mention the host, the database name, the user name & the password too. Refer following example.

import mysql.connector

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='electronics',
                                         user='pynative',
                                         password='pynative@#29')

    sql_select_Query = "select * from Laptop"
    cursor = connection.cursor()
    cursor.execute(sql_select_Query)
    # get all records
    records = cursor.fetchall()
    print("Total number of rows in table: ", cursor.rowcount)

    print("\nPrinting each row")
    for row in records:
        print("Id = ", row[0], )
        print("Name = ", row[1])
        print("Price  = ", row[2])
        print("Purchase date  = ", row[3], "\n")

except mysql.connector.Error as e:
    print("Error reading data from MySQL table", e)
finally:
    if connection.is_connected():
        connection.close()
        cursor.close()
        print("MySQL connection is closed")

If you want more details, refer to this link which I extracted above code sample.

  • Related