Loading

sqlite3-python

官网资料

https://sqlite.org/lang_createtable.html

操作参考:
https://www.runoob.com/sqlite/sqlite-insert.html

安装

Ubuntu安装

sudo  apt  install sqlite3

基本使用

1,创建数据库

sqlite3  tt.db

##在当前目录创建了一个库

2,查看库位置
命令行创建库成功后会在当前目录下新建一个库文件 tt.db,随即进入命令行模式

#查询库位置
sqlite> .databases
seq  name             file                                                      
---  ---------------  ----------------------------------------------------------
0    main             /home/yon/pycharm-code/proxy-pool/tt.db   


##查询表
sqlite> .tables
proxy


#帮助
sqlite> .help


3,创建表

sqlite> create  table proxy(id  INTEGER  PRIMARY KEY AUTOINCREMENT NOT NULL,ip  TEXT NOT NULL , port TEXT NOT NULL ,pro TEXT NOT NULL);

4,插入数据

sqlite> insert into proxy(ip,port,pro) values("114.114.114.114","8080","http");

5,查询数据


sqlite> select * from  proxy;
1|114.114.114.114|8080|http

python使用

官网文档
https://docs.python.org/zh-cn/3.8/library/sqlite3.html

#创建一个连接对象
import sqlite3
conn = sqlite3.connect('example.db')


#创建游标对象
1,基本操作
c = conn.cursor()

# Create table
c.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text, qty real, price real)''')

# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")


##打印查询结果,游标对象只能打印一次,过后需要重新执行查询操作
for x  in c.execute("select  * from proxy"): print(x)


# Save (commit) the changes
conn.commit()

# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()

2,查询语句可控
不应该使用 Python 的字符串操作来创建你的查询语句

# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())

# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
             ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
            ]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)


##一个使用迭代器形式的例子
>>> for row in c.execute('SELECT * FROM stocks ORDER BY price'):
        print(row)

('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
('2006-04-06', 'SELL', 'IBM', 500, 53.0)
('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)

posted @ 2019-12-15 16:30  Lust4Life  阅读(576)  评论(0编辑  收藏  举报