[英]how to insert in mysql database using python
我正在寫一個python腳本,它允許插入到數據庫mysql中。 它沒有錯誤,並且“ select *” Python代碼提供了我發布的列表,但是當我在終端中編寫mysql -u root -p
並select *
它僅給出了我從終端放入數據庫的行–我從代碼中插入的那行不存在。
請你幫我一下。 謝謝。
cur.execute("INSERT INTO ALL_DEVICES(HOST_NAME,ADDRESS_MAC,ADDRESS_IP,TIME_SCAN,DATE,ETAT) VALUES(%s,%s,%s,%s,%s,%s)",(host_name1, address_mac1,address_ip1,time_scan1,date1,etat))
cur.execute("SELECT * FROM ALL_DEVICES")
rows = cur.fetchall()
print rows
結果是:
((2L, 'LKK', 'LLKK', 'KLK', 'KK', 'KJH', 'KLO'), (4L, 'LKK', 'LLKK', 'KLK', 'KK', 'KJH', 'KLO'), (5L, 'host_name1', 'address_mac1', 'address_ip1', 'tim', 'da', 'etat'), (9L, 'host_name1', 'address_mac1', 'address_ip1', 'tim', 'da', 'etat'), (19L, '', 'D8:3C:69:AA:02:E9', '192.168.1.3', '14:07', '21/03/15', 'Interdit'), (20L, '', 'D8:3C:69:AA:02:E9', '192.168.1.2', '4:07', '21/03/15', 'Interdit'), (21L, '', '2C:E4:12:54:7D:4F', '192.168.1.1', '14:07', '21/03/15', 'Interdit'))
然后在終端中選擇*給我:
mysql> select * from ALL_DEVICES;
| Id | HOST_NAME | ADDRESS_MAC | ADDRESS_IP | TIME_SCAN | DATE | ETAT |
+----+------------+--------------+-------------+-----------+------+------+
| 2 | LKK | LLKK | KLK | KK | KJH | KLO |
| 4 | LKK | LLKK | KLK | KK | KJH | KLO |
| 5 | host_name1 | address_mac1 | address_ip1 | tim | da | etat |
| 9 | host_name1 | address_mac1 | address_ip1 | tim | da | etat |
+----+------------+--------------+-------------+-----------+------+------+
4 rows in set (0,00 sec)
您必須使用.commit()
。
讓
conn = connect("database")
cur = conn.cursor()
cur.execute("INSERT into ...") #insert query
conn.commit() #you missed it
cur.execute("SELECT ...") #select query
itzmeontv說的是正確的。 除非您commit(),否則對數據庫的更改將不會保存。
從Python與sql數據庫進行交互的另一種方法是使用“ sqlalchemy”模塊。 這是一般流程:
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
database = "sqlite:////" + path + "/" + db_file
self.engine = create_engine(database)
Session = sessionmaker()
Session.configure(bind=self.engine)
self.session = Session()
self.base = Base
# An example Table called train_info
class Traininfo(Base):
__tablename__ = "train_info"
train_name = Column(String(250), primary_key=True)
from_station = Column(String(150))
to_station = Column(String(150))
direction = Column(String(2))
mode = Column(String(2))
date = Column(String(64))
# Creating table and saving records in the table.
train_info = Traininfo(train_name = train_record[0],
from_station=train_record[1],
to_station=train_record[2],
direction=str(train_record[3]),
mode=str(train_record[4]),
date = train_record[5])
train_info.__table__.create(self.engine, checkfirst = True)
self.session.add(train_info)
self.session.commit()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.