本文整理汇总了Python中sqlite3.connect函数的典型用法代码示例。如果您正苦于以下问题:Python connect函数的具体用法?Python connect怎么用?Python connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了connect函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: iniciar
def iniciar (self) : # definicion del metodo
menu = '1 : añadirDVD - 2 : editarDVD - 3 : buscarDVD - 4 : listaDVDs - 5 : borrarDVD - S : salir \n' # asigna cadena menu
if os.path.exists ('./Escritorio/baseDatos.sql') : # condicion , si existe el fichero en la ruta indicada devuelve True
baseDATOS_SQL = sqlite3.connect ('./Escritorio/baseDatos.sql') # abre el fichero creado con el modulo sqlite3 , si no existe lo crea
else : # si no existe ; False
baseDATOS_SQL = sqlite3.connect ('./Escritorio/baseDatos.sql') # abre el fichero creado con el modulo sqlite3 , si no existe lo crea
cursor = baseDATOS_SQL.cursor () # crea el objeto que ejecuta las llamadas SQL
cursor.execute ('CREATE TABLE dvds (titulo TEXT UNIQUE NOT NULL,director TEXT NOT NULL,año INTEGER NOT NULL,duracion INTEGER NOT NULL)') # ejecuta las llamadas SQL en la base de datos del objeto -crea la tabla dvds con las columnas ; titulo , director , año ,duracion-
baseDATOS_SQL.commit () # guarda los cambios en el fichero SQL del objeto
while True : # bucle while continuo
print (menu) # presenta el menu
entradaTeclado = input ('entre opcion >> ') # espera entrada teclado
print ('\n') # salto de linea
if entradaTeclado == '1' : # condicion , si se cumple
self.añadirDVD (baseDATOS_SQL) # llama al metodo con el argumento indicado -objeto sqlite3-
elif entradaTeclado == '2' : # condicion , si se cumple
self.editarDVD (baseDATOS_SQL) # llama al metodo con el argumento indicado -objeto sqlite3-
elif entradaTeclado == '3' : # condicion , si se cumple
self.buscarDVD (baseDATOS_SQL) # llama al metodo con el argumento indicado -objeto sqlite3-
elif entradaTeclado == '4' : # condicion , si se cumple
self.listaDVDs (baseDATOS_SQL) # llama al metodo con el argumento indicado -objeto sqlite3-
elif entradaTeclado == '5' : # condicion , si se cumple
self.borrarDVD (baseDATOS_SQL) # llama al metodo con el argumento indicado -objeto sqlite3-
elif entradaTeclado == 'S' or entradaTeclado == 's' : # condicion , si se cumple
baseDATOS_SQL.close () # cierra el fichero de la base de datos
sys.exit (1) # sale del script
else : # ninguna de las opciones indicadas
continue # vuelve al inicio del bucle
开发者ID:jvpb,项目名称:PYTHON3,代码行数:28,代码来源:capitulo11.py
示例2: alias_register
def alias_register(alias_desired):
reg_string = "alias=" + alias_desired
if full_ledger == 1:
conn = sqlite3.connect('static/ledger.db')
else:
conn = sqlite3.connect('static/hyper.db')
conn.text_factory = str
c = conn.cursor()
m.execute("SELECT timestamp FROM transactions WHERE openfield = ?;", (reg_string,))
registered_pending = m.fetchone()
c.execute("SELECT timestamp FROM transactions WHERE openfield = ?;", (reg_string,))
registered_already = c.fetchone()
if registered_already == None and registered_pending == None:
alias_cb_var.set(0)
send_confirm("0", address, "1", reg_string)
else:
top9 = Toplevel()
top9.title("Name already registered")
registered_label = Label(top9, text="Name already registered")
registered_label.grid(row=0, column=0, sticky=N + W, padx=15, pady=(5, 0))
dismiss = Button(top9, text="Dismiss", command=top9.destroy)
dismiss.grid(row=3, column=0, sticky=W + E, padx=15, pady=(5, 5))
开发者ID:zhilinwww,项目名称:Bismuth,代码行数:28,代码来源:legacy_gui.py
示例3: _getDb
def _getDb(self, channel):
filename = plugins.makeChannelFilename(self.filename, channel)
if filename in self.dbs:
return self.dbs[filename]
if os.path.exists(filename):
db = sqlite3.connect(filename)
db.text_factory = str
self.dbs[filename] = db
return db
db = sqlite3.connect(filename)
db.text_factory = str
self.dbs[filename] = db
cursor = db.cursor()
cursor.execute("""CREATE TABLE karma (
id INTEGER PRIMARY KEY,
name TEXT,
normalized TEXT UNIQUE ON CONFLICT IGNORE,
added INTEGER,
subtracted INTEGER
)""")
db.commit()
def p(s1, s2):
return int(ircutils.nickEqual(s1, s2))
db.create_function('nickeq', 2, p)
return db
开发者ID:Criptomonedas,项目名称:supybot_fixes,代码行数:25,代码来源:plugin.py
示例4: patent_hunter
def patent_hunter(option=0, patinfo=""):
print 'option : ', option
print 'patent info : ', patinfo
assert option!=0 and patinfo!="" # option must not be zero
writer = csv.writer(open('./result.csv','w'))
psyinfo = '06304546'
# Citation sqlite3
if option == 'patnum' or option == '1':
opensql = sqlite3.connect("/home/minyoon/citation.sqlite3")
# Inventor sqlite3
elif option == 'inventor' or option == '2':
opensql = sqlite3.connect("/home/minyoon/full_disambiguation.sqlite3")
if opensql!=None:
cur = opensql.cursor()
if option == 'patent' or option == '1':
# list of patent that this patent is referencing
#cur.execute("SELECT Citation FROM citation WHERE Patent=? LIMIT 50", (patinfo,))
# list of patent that references this patent
cur.execute("SELECT Patent FROM citation WHERE Citation=?", (patinfo,))
elif option == 'inventor' or option == '2':
cur.execute("SELECT Patent FROM invpat WHERE Lastname = ? Limit 50", (patinfo,))
for entry in cur.fetchall():
print entry
return 1
开发者ID:minyoon,项目名称:PatHunt,代码行数:27,代码来源:patent_hunter.py
示例5: init_db
def init_db(self):
db = os.path.join(self.local_path, "db")
if os.access(db, os.R_OK):
self.conn = sqlite3.connect(db)
self.c = self.conn.cursor()
self.c.execute(
"""
select root_dir, backup_dir, freq, start_time
from backup_unit"""
)
for row in self.c:
task = Task(row[0], row[1], row[2], row[3])
self.task_list.append([task] + list(row))
else:
self.conn = sqlite3.connect(db)
self.c = self.conn.cursor()
self.c.executescript(
"""
create table backup_unit(
root_dir varchar, backup_dir varchar, freq varchar, start_time varchar);
create table snapshot_unit(
root_dir varchar, snapshot varchar, cur_time varchar);
create table log(
user varchar, message varchar, time varchar);
create table dir_state(
root_dir varchar, cur_state varchar);
"""
)
开发者ID:zorgan,项目名称:Bronze-Hamster,代码行数:31,代码来源:transparent.py
示例6: initDB
def initDB():
#データベースにファイルを作る
if not os.path.exists(u"data.db"):
con = sqlite3.connect(u"data.db")
con.execute(u"""
create table Picture(
path_orig varchar(128),
path_link varchar(128),
path_thumb1 varchar(128),
path_thumb2 varchar(128),
flag integer,
last_update real,
tags varchar(128),
dir varchar(128),
name varchar(128),
primary key (path_orig)
);
""")
con.execute(u"""
create table Dir(
path_orig varchar(128),
flag integer,
last_update varchar(128),
date varchar(128),
name varchar(128),
fileNum integer,
primary key (path_orig)
);
""")
else:
con = sqlite3.connect(u"data.db")
con.close()
开发者ID:s0-ma,项目名称:photium,代码行数:32,代码来源:init.py
示例7: mainpage
def mainpage(imagename=None):
if request.method == 'GET':
if imagename:
imgname=(imagename,)
con = sqlite3.connect('Image.db')
cur = con.cursor()
cur.execute("SELECT * FROM Image WHERE imgname=?", imgname)
rows = cur.fetchall()
if rows:
for row in rows:
imgname = row[0]
imgdata = row[1]
return render_template('paint.html', saved=imgdata)
else:
resp = Response("""<html> <script> alert("Image not found");document.location.href="/" </script> </html>""")
return resp
else:
return render_template('paint.html')
if request.method == 'POST':
imgname=request.form['imagename']
imgdata=request.form['string']
data=(imgname, imgdata)
con = sqlite3.connect("Image.db")
cur=con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS Image(imgname text, imgdata string)")
cur.execute("INSERT INTO Image VALUES(?, ?)", data)
con.commit()
con.close()
resp = Response("saved")
return resp
开发者ID:shinasnp,项目名称:paint_app_using_flask,代码行数:30,代码来源:test.py
示例8: test_new_geopackage
def test_new_geopackage(self):
assert os.path.exists(self.gpkg_file)
with sqlite3.connect(self.gpkg_file) as db:
cur = db.execute('''SELECT name FROM sqlite_master WHERE type='table' AND name=?''',
(self.table_name,))
content = cur.fetchone()
assert content[0] == self.table_name
with sqlite3.connect(self.gpkg_file) as db:
cur = db.execute('''SELECT table_name, data_type FROM gpkg_contents WHERE table_name = ?''',
(self.table_name,))
content = cur.fetchone()
assert content[0] == self.table_name
assert content[1] == 'tiles'
with sqlite3.connect(self.gpkg_file) as db:
cur = db.execute('''SELECT table_name FROM gpkg_tile_matrix WHERE table_name = ?''',
(self.table_name,))
content = cur.fetchall()
assert len(content) == 20
with sqlite3.connect(self.gpkg_file) as db:
cur = db.execute('''SELECT table_name FROM gpkg_tile_matrix_set WHERE table_name = ?''',
(self.table_name,))
content = cur.fetchone()
assert content[0] == self.table_name
开发者ID:LKajan,项目名称:mapproxy,代码行数:27,代码来源:test_cache_geopackage.py
示例9: regendb2
def regendb2():
conn = sqlite3.connect('list2.db')
c = conn.cursor()
c.execute("select * from statics")
if os.path.exists('list3.db')==False:
conn2 = sqlite3.connect('list3.db')
c2 = conn2.cursor()
c2.execute("CREATE TABLE statics (id,name,sex,class,major,college,collegeid)")
else:
conn2 = sqlite3.connect('list3.db')
c2 = conn2.cursor()
for result in c.fetchall():
studentid=result[0]
studentname=result[1]
studentsex=result[2]
studentclass=result[3]
studentmajor=result[4]
studentcollege=result[5]
collegeid=result[6]
if studentsex=="男".decode("utf8"):
ensex=0
elif studentsex=="女".decode("utf8"):
ensex=1
c2.execute("insert into statics values ('"+studentid+"','"+studentname+"','"+str(ensex)+"','"+studentclass+"','"+studentmajor+"','"+studentcollege+"','"+str(collegeid)+"')")
conn2.commit()
c2.close()
conn2.close()
conn.commit()
c.close()
conn.close()
开发者ID:xulihang,项目名称:misc,代码行数:33,代码来源:index.py
示例10: __init__
def __init__(self,string):
if not ( os.path.isfile("{0}/{1}.db".format(self.LOCAL,string)) ):
self.conn = sqlite3.connect(string + ".db")
self.c = self.conn.cursor()
self.c.execute(''' CREATE TABLE user (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, cpf text, data_nascimento date)''')
self.conn.commit()
self.dbname = string
elif os.path.isfile( "{0}/{1}.db".format(self.LOCAL,string) ):
self.conn = sqlite3.connect(string + ".db")
self.c = self.conn.cursor()
self.dbname = string
elif os.path.isfile( "{0}/appdb.db".format(self.LOCAL) ):
self.conn = sqlite3.connect("appdb.db")
self.c = self.conn.cursor()
self.dbname = "appdb"
else:
self.conn = sqlite3.connect("appdb.db")
self.c = self.conn.cursor()
self.c.execute(''' CREATE TABLE user (id INTEGER PRIMARY KEY AUTOINCREMENT, name text, cpf text, data_nascimento date)''')
conn.commit()
self.dbname = "appdb"
开发者ID:marcossaito,项目名称:cadastro-pessoa,代码行数:27,代码来源:dbservice.py
示例11: open
def open(self):
if os.path.exists(self.filename):
db = sqlite3.connect(self.filename, check_same_thread = False)
db.text_factory = str
self.db = db
return
db = sqlite3.connect(self.filename, check_same_thread = False)
db.text_factory = str
self.db = db
cursor = self.db.cursor()
cursor.execute("""CREATE TABLE users (
id INTEGER PRIMARY KEY,
total_rating INTEGER,
created_at INTEGER,
pos_rating_recv_count INTEGER,
neg_rating_recv_count INTEGER,
pos_rating_sent_count INTEGER,
neg_rating_sent_count INTEGER,
nick TEXT UNIQUE ON CONFLICT REPLACE,
host TEXT)
""")
cursor.execute("""CREATE TABLE ratings (
id INTEGER PRIMARY KEY,
rated_user_id INTEGER,
rater_user_id INTEGER,
created_at INTEGER,
rating INTEGER,
notes TEXT)
""")
self._commit()
return
开发者ID:Criptomonedas,项目名称:supybot-bitcoin-marketmonitor,代码行数:32,代码来源:plugin.py
示例12: __init__
def __init__(self, path):
conn = sqlite3.connect(path, check_same_thread=False)
if os.path.exists(path) and os.path.isfile(path):
self.conn = conn
else:
Log.error('Create sqlite3 file fail. use memory!')
self.conn = sqlite3.connect(':memory:')
开发者ID:colin-zhou,项目名称:reserve,代码行数:7,代码来源:original_py_file.py
示例13: searching
def searching(self,entry,model):
lista_hist[:] = []
lista_histfull[:] = []
connb = sqlite3.connect(path + 'turbo.db')
a = connb.cursor()
a.execute("SELECT id,nome,conteudo,data,tipo,ip FROM history where conteudo like '%" + entry.get_text() + "%' order by id desc")
rows = a.fetchall()
for history in rows:
if history[4] == "S":
lista_hist.append([str(history[0]),history[1],cap(history[2],200),history[3],ico_send,history[5]])
else:
lista_hist.append([str(history[0]),history[1],cap(history[2],200),history[3],ico_receive,history[5]])
connc = sqlite3.connect(path + 'turbo.db')
c = connc.cursor()
c.execute("SELECT id,nome,conteudo,data,tipo,ip FROM history where conteudo like '%" + entry.get_text() + "%' order by id desc")
rowsc = c.fetchall()
for history in rowsc:
if history[4] == "S":
lista_histfull.append([str(history[0]),history[1],history[2].encode("utf-8"),history[3],ico_send,history[5]])
else:
lista_histfull.append([str(history[0]),history[1],history[2].encode("utf-8"),history[3],ico_receive,history[5]])
connb.close()
if len(model) != 0:
for i in range(len(model)):
iter = model.get_iter(0)
model.remove(iter)
for i in range(len(lista_hist)):
model.append(lista_hist[i])
开发者ID:PrimaMateria,项目名称:cinnamon-spices-applets,代码行数:34,代码来源:historic.py
示例14: add_cb
def add_cb(self, button,column,treesortable):
nome = self.nometxt.get_text()
connb = sqlite3.connect(path + 'turbo.db')
a = connb.cursor()
a.execute("SELECT nome FROM contacts WHERE upper(nome) = upper('" + nome + "')")
contactsName = a.fetchone()
connb.close()
if not contactsName:
if nome != "nome":
try:
IP = socket.gethostbyname(nome)
connc = sqlite3.connect(path + 'turbo.db')
c = connc.cursor()
c.execute("INSERT INTO contacts (nome,ip) VALUES (?,?)",(nome.upper(),IP))
connc.commit()
connc.close()
command = "mkdir " + path_attached + nome.upper()
os.system(command)
self.listmodel.append([nome.upper(),IP])
treesortable.set_sort_column_id(1, Gtk.SortType.ASCENDING)
except socket.gaierror, err:
msgerror = "I can't ping this host name!\\nPlease chech the host name and try again!";
command = "notify-send --hint=int:transient:1 \"TurboNote Gnome3\" \"" + (msgerror).decode('iso-8859-1').encode('utf8') + "\" -i " + path_icon + "turbo.png"
os.system(command)
else:
msgerror = "No data Found!\\nPlease i need contact name and ip adress for save contact!";
command = "notify-send --hint=int:transient:1 \"TurboNote Gnome3\" \"" + (msgerror).decode('iso-8859-1').encode('utf8') + "\" -i " + path_icon + "turbo.png"
os.system(command)
开发者ID:iksws,项目名称:GnomeTurboNoteExtension,代码行数:28,代码来源:contacts.py
示例15: makeDb
def makeDb(self, filename):
if os.path.exists(filename):
db = sqlite3.connect(filename)
if sys.version_info[0] < 3:
db.text_factory = str
return db
db = sqlite3.connect(filename)
if sys.version_info[0] < 3:
db.text_factory = str
cursor = db.cursor()
cursor.execute("""CREATE TABLE keys (
id INTEGER PRIMARY KEY,
key TEXT UNIQUE ON CONFLICT REPLACE
)""")
cursor.execute("""CREATE TABLE factoids (
id INTEGER PRIMARY KEY,
added_by TEXT,
added_at TIMESTAMP,
fact TEXT UNIQUE ON CONFLICT REPLACE,
locked BOOLEAN
)""")
cursor.execute("""CREATE TABLE relations (
id INTEGER PRIMARY KEY,
key_id INTEGER,
fact_id INTEGER,
usage_count INTEGER
)""")
db.commit()
return db
开发者ID:gerdesas,项目名称:Limnoria,代码行数:29,代码来源:plugin.py
示例16: generate_sqlite
def generate_sqlite(self):
print "Converting csv file to sqlite for train set:"
num_lines = sum(1 for line in open(self.folder+self.file_in))
columns = ['TRIP_ID', 'CALL_TYPE', 'ORIGIN_CALL', 'ORIGIN_STAND', 'TAXI_ID',
'TIMESTAMP', 'DAYTYPE', 'MISSING_DATA', 'POLYLINE']
con = sqlite3.connect(self.folder+self.file_out)
chunk_size = 5000
count = 1
for i in range(0, num_lines, chunk_size):
df = pd.read_csv(self.folder+self.file_in, header=None,
nrows=chunk_size, skiprows=i, low_memory=False)
df.columns = columns
sql.to_sql(df, name='train_data', con=con, index=False,
index_label='molecule_id', if_exists='append')
print "Batch No. {} completed".format(count)
count += 1
con.close()
# Delete the first row with duplicate column names
con = sqlite3.connect(self.folder+self.file_out)
c = con.cursor()
c.execute("DELETE FROM train_data WHERE TRIP_ID='TRIP_ID'")
con.commit()
con.close()
print "All completed!\n"
开发者ID:ffyu,项目名称:Kaggle-Taxi-Travel-Time-Prediction,代码行数:32,代码来源:Submission.py
示例17: __init__
def __init__(self, db_file):
try:
import sqlite3
except ImportError:
raise ImportError, "You need sqlite3 to use this storage backend"
import os.path
if not os.path.exists(db_file):
self.conn = sqlite3.connect(db_file)
self.conn.text_factory = str
cursor = self.conn.cursor()
cursor.execute(
"""
CREATE TABLE occurrences(
class TEXT,
feature TEXT,
occurrences INTEGER,
PRIMARY KEY(feature, class)
)
"""
)
self.conn.commit()
cursor.close()
else:
self.conn = sqlite3.connect(db_file)
self.conn.text_factory = str
开发者ID:martinkirch,项目名称:tofbot,代码行数:25,代码来源:classifier.py
示例18: connection
def connection(path):
"""Return the connection and the cursor for doing
some stuff in the db
path -String- absolute PATH of your db
"""
db = path #open 'database'
return sqlite3.connect(db), sqlite3.connect(db).cursor() #connect to current database
开发者ID:Piplopp,项目名称:hepc_retro_db,代码行数:7,代码来源:hepc_python.py
示例19: __init__
def __init__(self, width=-1):
self.h=HistoryEngine()
self.tw=textwrap.TextWrapper()
self.tw.break_on_hyphens=False
self.width=width
if width!=-1: self.tw.width=width
self.prefix=self.guess_prefix()
self.db=os.path.join(self.prefix,'data.db')
self.cn=sqlite3.connect(self.db, check_same_thread = False)
self.c=self.cn.cursor()
self.langs=map(lambda a: a[0],self.c.execute(SQL_GET_LANGS).fetchall())
self.lang_boundary={}
for l in self.langs:
i=self.c.execute(SQL_GET_LANG_START, (l,)).fetchone()[0]
f=self.c.execute(SQL_GET_LANG_END, (l,)).fetchone()[0]
self.lang_boundary[l]=(i,f)
self.cn.row_factory=sqlite3.Row
self.c=self.cn.cursor()
self.fallback_lang='ar'
self.set_lang()
self.cities_db=os.path.join(self.prefix,'cities.db')
self.cities_cn=sqlite3.connect(self.cities_db)
self.cities_cn.row_factory=sqlite3.Row
self.cities_c=self.cities_cn.cursor()
r=self.cities_c.execute('select v from params where k=?', ('ver',)).fetchone()
print dict(r)
if r: self.cities_db_ver=r['v']
else: self.cities_db_ver='0'
开发者ID:ojuba-org,项目名称:monajat,代码行数:29,代码来源:monajat.py
示例20: _initialize_session_cache
def _initialize_session_cache(self):
# Note -- fallback to returning None on any problems as this isn't
# critical. It just makes it so that we don't have to ask the user
# for their password over and over.
if not os.path.isdir(b_SESSION_DIR):
try:
os.makedirs(b_SESSION_DIR, mode=0o755)
except OSError as err:
log.warning('Unable to create {file}: {error}').format(
file=b_SESSION_DIR, error=err)
return None
if not os.path.exists(b_SESSION_FILE):
dbcon = sqlite3.connect(b_SESSION_FILE)
cursor = dbcon.cursor()
try:
cursor.execute('create table sessions (username text,'
' base_url text, session_id text,'
' primary key (username, base_url))')
except sqlite3.DatabaseError as err:
# Probably not a database
log.warning('Unable to initialize {file}: {error}'.format(
file=b_SESSION_FILE, error=err))
return None
dbcon.commit()
else:
try:
dbcon = sqlite3.connect(b_SESSION_FILE)
except sqlite3.OperationalError as err:
# Likely permission denied
log.warning('Unable to connect to {file}: {error}'.format(
file=b_SESSION_FILE, error=err))
return None
return dbcon
开发者ID:fandikurnia,项目名称:python-fedora,代码行数:34,代码来源:openidbaseclient.py
注:本文中的sqlite3.connect函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论