Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

python - Data not saving SQLite3 python3.4

I am currently trying to create a sqlite database of peoples names and ip While my code seems to work when I run it the data doesn't show up when I run SELECT * from ips; in terminal after running SQLite3 ips Below is my code. Both it and the SELECT * from ips; are running in ~/Desktop/SQL

import sqlite3 as sql
import socket
import struct
def iptoint(ip):
    return str(struct.unpack("i",socket.inet_aton(ip))[0])


database = sql.connect("ips")
createTable = True
if createTable:
    database.execute('''CREATE TABLE main.ips
    (FIRST_NAME TEXT PRIMARY KEY NOT NULL,
    SECOND_NAME TEXT NOT NULL,
    IP INT32 NOT NULL);''')

sampleIps = [("Edward","E","60.222.168.44")]
for first,second,ip in sampleIps:
    string = "INSERT INTO ips VALUES ('%s','%s','%s');"%(first,second,iptoint(ip))
    print(string)
    #Printing the string gives me INSERT INTO ips VALUES ('Edward','E','749264444');
    database.execute("INSERT INTO ips VALUES ('%s','%s','%s');"%(first,second,iptoint(ip)))

database.close()

My computer is running OSX 10.11.4, python 3.4 and SQLite 3.14.1

I have tried changing ips to main.ips and back


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It doesn't look like you are committing to the database. You need to commit before closing the connection in order to actually save your changes to the database.

database.commit()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...