连接数据库

 1 # -*-coding:gb2312-*-
 2 
 3 #Function:数据库的基本操作
 4 #Author:LiXia
 5 #Version:V 1.0.0.1
 6 
 7 #主要包括建表、插入数据、查询以及打印输出查询结果等
 8 
 9 import sqlite3         #第一步:导入包
10  
11 conn = sqlite3.connect('E:/Python-Program/database/base.db')    #第二步:连接数据库,这里用的是绝对路径,其实应该用相对路径+sys方法
12 curs = conn.cursor()    #第三步:获取游标
13 
14 #建表
15 conn.execute("""
16 CREATE TABLE IF NOT EXISTS phonebook(
17     name varchar,
18     phonenumber varchar
19 )
20 """)
21 
22 #SQL语句:Insert语句
23 insertSql = "Insert INTO phonebook(name, phonenumber) VALUES('lixia', '123456789')"
24 
25 curs.execute(insertSql)
26 
27 conn.commit()           #commit之后才能更新到本地数据库文件中
28 
29 #SQL语句:查询语句
30 querySql = "select * from phonebook where name = 'lixia'"
31 
32 curs.execute(querySql)
33 
34 res = curs.fetchone()
35 
36 if res == None:
37     print "There is nothing!"
38 else:
39     print res[0]
40     print res[1]
41 
42 curs.close()        
43 conn.close()  
原文地址:https://www.cnblogs.com/keke-xiaoxiami/p/3741320.html