如何使用“INSERT .... SELECT”在python? [英] How to use "INSERT....SELECT" in python?

查看:356
本文介绍了如何使用“INSERT .... SELECT”在python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的表格:

I have a table like this:

 ID     Candy - fruit           Index
101        banana                1
102        chocolate             0
103        orange                1
104        apple                 1
105        cake                  0



我想要选择所有行都有index = 1并使用python添加到fruit_table。

请帮帮我。谢谢!


I want to select all rows have index = 1 and add to fruit_table using python.
Please help me. Thanks!

推荐答案

检查本教程要点 [ ^ ]

SQLLITE [ ^ ]

你有没有提到你用于数据访问,我给了两个链接,一个使用MySql,另一个使用SqlLite。

希望这些帮助。

谢谢。

:)
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.
:)


使用标准的sql查询。



但是只有执行类型会有所不同,如图所示



use standard sql query.

But only execution type will be different as shown

#!/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()


这篇关于如何使用“INSERT .... SELECT”在python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆