Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a table like this:
CSS
 ID     Candy - fruit           Index
101        banana                1
102        chocolate             0
103        orange                1
104        apple                 1
105        cake                  0

I want to select all rows have index = 1 and add to fruit_table using python.
Please help me. Thanks!
Posted
Updated 9-Nov-14 22:26pm
Comments
Afzaal Ahmad Zeeshan 9-Nov-14 9:02am    
Give this a try. http://www.tutorialspoint.com/python/python_database_access.htm

Check this tutorial point[^]
SQLLITE[^]
You have not mentioned what you are using for Data access, I have given two links, one using MySql and other using SqlLite.
Hope these help.
Thanks.
:)
 
Share this answer
 
Comments
Member 10390715 10-Nov-14 4:15am    
Thank you
[no name] 10-Nov-14 4:15am    
You are always welcome. :)
use standard sql query.

But only execution type will be different as shown

Python
#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
         LAST_NAME, AGE, SEX, INCOME)
         VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

# disconnect from server
db.close()

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
sql = "SELECT * FROM EMPLOYEE \
       WHERE INCOME > '%d'" % (1000)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
      # Now print fetched result
      print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
             (fname, lname, age, sex, income )
except:
   print "Error: unable to fecth data"

# disconnect from server
db.close()
 
Share this answer
 
v2
Comments
Richard MacCutchan 9-Nov-14 13:42pm    
Please format your code so it is readable.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900