Пример #1
0
	def connect_db(self):
		try:
			if (self.params['-s']==''):# and self.params['-d']!=''):
				print self.params
				self.mydb=kdb.connect(host=self.params['-h'],database=self.params['-d'],user=self.params['-u'], password=self.params['-p'],dialect=3, charset='UTF8' )
			else:
				self.mydb=kdb.connect(dsn=self.params['-s'],user=self.params['-u'], password=self.params['-p'],dialect=3, charset='UTF8' )
			return self.mydb
		except:
			print 'Except'
			self.no_connect()
			return None
Пример #2
0
 def stopDB(self):
     import kinterbasdb
     conn = kinterbasdb.connect(database=self.DB_NAME,
                                host='127.0.0.1',
                                user=self.DB_USER,
                                password=self.DB_PASS)
     conn.drop_database()
Пример #3
0
 def makeConnection(self):
   customTPB = (kinterbasdb.isc_tpb_write + kinterbasdb.isc_tpb_read_committed
     + kinterbasdb.isc_tpb_rec_version)
   self.con = kinterbasdb.connect(dsn=self.dbname, user=self.login, password=self.passwd)
   self.con.begin(tpb=customTPB)
   self.cur = self.con.cursor()
   self.makeTables()
Пример #4
0
    def connect(self):
		
        import kinterbasdb
		
        try:
            kinterbasdb.init(type_conv=0)
        except:
            pass	
		
        self._db = kinterbasdb.connect(dsn=self._bdd,
                                       user=self._user,
                                       password=self._password,
                                       charset=self._charset)
        try:
            self._db.cursor().execute("DECLARE EXTERNAL FUNCTION lpad \
               CSTRING(255) NULL, INTEGER, CSTRING(1) NULL \
               RETURNS CSTRING(255) FREE_IT \
               ENTRY_POINT 'IB_UDF_lpad' MODULE_NAME 'ib_udf'")
        except:
            pass
        try:
            self._db.cursor().execute("DECLARE EXTERNAL FUNCTION Round \
                INT BY DESCRIPTOR, INT BY DESCRIPTOR \
                RETURNS PARAMETER 2 \
                ENTRY_POINT 'fbround' MODULE_NAME 'fbudf'")
        except:
            pass
Пример #5
0
 def stopDB(self):
     import kinterbasdb
     conn = kinterbasdb.connect(database=self.DB_NAME,
                                host='127.0.0.1', user=self.DB_USER,
                                password=self.DB_PASS)
     conn.drop_database()
     conn.close()
Пример #6
0
    def _cursor(self):
        if self.connection is None:
            settings_dict = self.settings_dict
            if settings_dict['NAME'] == '':
                from django.core.exceptions import ImproperlyConfigured
                raise ImproperlyConfigured("You need to specify DATABASE_NAME in your Django settings file.")
            conn_params = {
                'charset': 'UNICODE_FSS'
            }
            conn_params['dsn'] = settings_dict['NAME']
            if settings_dict['HOST']:
                conn_params['dsn'] = ('%s:%s') % (settings_dict['HOST'], conn_params['dsn'])
            if settings_dict['PORT']:
                conn_params['port'] = settings_dict['PORT']
            if settings_dict['USER']:
                conn_params['user'] = settings_dict['USER']
            if settings_dict['PASSWORD']:
                conn_params['password'] = settings_dict['PASSWORD']
            options = settings_dict['OPTIONS'].copy()
            # Normalization for databases with 'NONE', 'OCTETS' or 'ASCII' charset.
            encoding = options.pop('encoding', 'utf_8')
            conn_params.update(options)
            self.connection = Database.connect(**conn_params)
            self._type_translator.set_charset(self.connection.charset, encoding)
            connection_created.send(sender=self.__class__)

            if self.ops.firebird_version[0] >= 2:
                self.features.can_return_id_from_insert = True

        return FirebirdCursorWrapper(self.connection.cursor(), self._type_translator)
Пример #7
0
 def PegaListadoBanco(self):
     '''
     Pega os dados do banco de dados e salva na listaProdutos
     '''
     
     try:
         conn = kinterbasdb.connect(host="10.1.1.10",
                                database='C:\SIACPlus\siacCX.fdb',
                                user="******",
                                password="******",
                                charset="ISO8859_1"
                                )
         print "Conexão aberta"
         cur = conn.cursor()
         cur.execute('SELECT a.COD_PRODUTO, a.DESCRICAO, a.CODBARRAS, a.SALDOESTOQUE FROM ACADPROD a')
         print "Select executado"
         #print "Lista de Produtos: ", self.listadeProdutos
         # Pegando dados do select e salvando em lista produtos, no momento salvando com estoque zero
         
         for i in cur:
             
             (cod_prod, descr, codbarras, saldoestoque) = i
             
             self.adicionaProdutos(cod_prod, descr, codbarras, saldoestoque)
         
         print "Produtos adicionados a lista"
         
         # Fechando acesso ao banco                
         conn.close()
         print "Conexão fechada"
         
     except:
         print "Erro ao acessar o banco"
     finally:
         print "Dados salvo com sucesso"
Пример #8
0
	def connect(self):
		if self.rdbms == 'mssql':
			import socket   #( To get the computer name for a SQL Server instance.
			import ipymssql #( Custom IronPython .NET Data Provider for SQL Server

			Instance = socket.gethostname() + r"\SILFW"
			Database = 'TestLangProj'
			conStr = 'Data Source=%s; Initial Catalog=%s; Integrated Security=True' % (Instance, Database)
			con = ipymssql.connect(conStr)

		elif self.rdbms == 'fb' or self.rdbms == 'firebird':
			import kinterbasdb #( http://kinterbasdb.sourceforge.net

			#( kinterbasdb must be initialized for life to be happy. See
			#( "Incompatibilities" at the top of:
			#(
			#(    http://kinterbasdb.sourceforge.net/dist_docs/usage.html
			#(
			#( The default for kinterbasdb.init is only for backward compatibility.
			#( The reasons for this are written up at:
			#(
			#(    http://kinterbasdb.sourceforge.net/dist_docs/usage.html#faq_fep_is_mxdatetime_required
			#(
			#( The ideal is to use type_conv=200

			kinterbasdb.init(type_conv=200)

			con = kinterbasdb.connect(
				dsn = 'C:\Program Files\Firebird_2_0\Data\TESTLANGPROJ.FDB',
				user = "******",
				password = "******",
				charset = 'UTF8',
				dialect = 3)

		return con
Пример #9
0
 def GetConnect(self):
     self.connect = None
     self.db_message = ''
     if self.k_conf.status_config == krconst.kr_status_config_error:
         self.db_message = self.k_conf.status_config_message
     try:
         self.connect = FB.connect(dsn=self.k_conf.db_ip + ':' +
                                   self.k_conf.db_path,
                                   user=self.k_conf.db_user,
                                   password=self.k_conf.db_pass,
                                   role=self.k_conf.db_role,
                                   charset=self.k_conf.db_charset)
         # self.connect.begin()
         self.cursor = self.connect.cursor()
     except:
         #print 'self.db_message', sys.exc_value[0]
         #print 'self.db_message', sys.exc_value[1]
         #print sys.exc_value[1].find('Unable to complete network request to host')
         if sys.exc_value[
                 0] == -902:  #and sys.exc_value[1].find('Unable to complete network request to host')!=-1:
             #print 'bed connection'
             self.db_message = sys.exc_value[1]
         else:
             self.db_message = sys.exc_value[0]
     return True
Пример #10
0
def openFB():
  config = ConfigParser.ConfigParser()
  config.read('config.cfg')

  conFB = kinterbasdb.connect(dsn=config.get('fb', 'host')+':'+config.get('fb', 'dbname'), \
                user=config.get('fb','user'), \
                password=config.get('fb', 'password'), \
                charset=config.get('fb', 'charset'), \
                dialect=config.getint('fb', 'dialect'))
  return conFB, conFB.cursor()
Пример #11
0
def openFB():
    config = ConfigParser.ConfigParser()
    config.read('config.cfg')

    conFB = kinterbasdb.connect(dsn=config.get('fb', 'host')+':'+config.get('fb', 'dbname'), \
                  user=config.get('fb','user'), \
                  password=config.get('fb', 'password'), \
                  charset=config.get('fb', 'charset'), \
                  dialect=config.getint('fb', 'dialect'))
    return conFB, conFB.cursor()
Пример #12
0
 def CleanUp(self, result):
     # Drop a database.
     try:
         self.__con = kinterbasdb.connect(dsn=str(self.__database_path), \
             user=str(self.user_name), password=str(self.user_password))
         self.__con.drop_database()
     except Exception, error:
         # Cleanup failed.
         cause = "Database deletion failed.  %s" % str(error)
         result.Fail(cause)
Пример #13
0
    def connect(self):
        self.initConnection()

        if not self.hostname:
            self.checkFileDb()

        try:
            self.connector = kinterbasdb.connect(host=self.hostname.encode(UNICODE_ENCODING), database=self.db.encode(UNICODE_ENCODING), \
                user=self.user.encode(UNICODE_ENCODING), password=self.password.encode(UNICODE_ENCODING), charset="UTF8")  # Reference: http://www.daniweb.com/forums/thread248499.html
        except kinterbasdb.OperationalError, msg:
            raise SqlmapConnectionException(msg[1])
Пример #14
0
    def connect(self):
        self.initConnection()

        if not self.hostname:
            self.checkFileDb()

        try:
            self.connector = kinterbasdb.connect(host=self.hostname.encode(UNICODE_ENCODING), database=self.db.encode(UNICODE_ENCODING), \
                user=self.user.encode(UNICODE_ENCODING), password=self.password.encode(UNICODE_ENCODING), charset="UTF8")  # Reference: http://www.daniweb.com/forums/thread248499.html
        except kinterbasdb.OperationalError, msg:
            raise SqlmapConnectionException(msg[1])
Пример #15
0
    def connect(self, dbname, user, passwd, host, **kwargs):
        try:
            import kinterbasdb
        except:
            print "Missing Firebird support through kinterbasdb"
            return

        self.strDbms = "firebird"
        self.version = kwargs.get("version")
        self.conn = kinterbasdb.connect(dsn="localhost:%s" % dbname, user=user, password=passwd)
        self.cursor = self.conn.cursor()
Пример #16
0
 def __init__(self, DBFileName):
     """
 Конструктор. Принимает в качестве аргумента имя файла базы данных
 и устанавливает с ней соединение 
 """
     self.con = k.connect(
         host=None, database=DBFileName, user="******", password="******", dialect=3, charset="WIN1251"
     )
     customTPB = k.isc_tpb_shared
     # Explicitly start a transaction with the custom TPB:
     self.con.begin(tpb=customTPB)
     self.curs = self.con.cursor()
Пример #17
0
    def fireBirdTests(self, bExec=True):
        try:
            import kinterbasdb
        except:
            print "Missing Firebird support through kinterbasdb"
            return

        self.strDbms = "firebird"
        info = conn_info[self.strDbms]
        self.conn = kinterbasdb.connect(dsn="localhost:%s" % info["dbname"], user=info["user"], password=info["pass"])

        ddt = DbDmlTest.DbDmlTest(self.strDbms, self.testList, log)
        ddt.doTests(self.conn, info["version"], bExec=bExec)
Пример #18
0
    def connect(self, info):
        try:
            import kinterbasdb
        except:
            print "Missing Firebird support through kinterbasdb"
            return

        self.strDbms = 'firebird'
        self.version = info['version']
        self.conn = kinterbasdb.connect(dsn='localhost:%s' % info['dbname'],
                                        user=info['user'],
                                        password=info['pass'])
        self.cursor = self.conn.cursor()
Пример #19
0
    def connect(self, dbname, user, passwd, host, **kwargs):
        try:
            import kinterbasdb
        except:
            print "Missing Firebird support through kinterbasdb"
            return

        self.strDbms = 'firebird'
        self.version = kwargs.get('version')
        self.conn = kinterbasdb.connect(dsn='localhost:%s' % dbname,
                                        user=user,
                                        password=passwd)
        self.cursor = self.conn.cursor()
Пример #20
0
 def makeConnection(self):
     extra = {}
     if self.dialect:
         extra['dialect'] = self.dialect
     return kinterbasdb.connect(
         host=self.host,
         database=self.db,
         user=self.user,
         password=self.passwd,
         role=self.role,
         charset=self.charset,
         **extra
         )
Пример #21
0
 def connect(self, info):
     try:
         import kinterbasdb
     except:
         print "Missing Firebird support through kinterbasdb"
         return
     
     self.strDbms = 'firebird'
     self.version = info['version']
     self.conn = kinterbasdb.connect(
         dsn='localhost:%s' % info['dbname'],
         user = info['user'], 
         password = info['pass'])
     self.cursor = self.conn.cursor()
Пример #22
0
    def connect(self):
        self.initConnection()

        if not self.hostname:
            self.checkFileDb()

        try:
            # Reference: http://www.daniweb.com/forums/thread248499.html
            self.connector = kinterbasdb.connect(host=self.hostname.encode(UNICODE_ENCODING), database=self.db.encode(UNICODE_ENCODING), user=self.user.encode(UNICODE_ENCODING), password=self.password.encode(UNICODE_ENCODING), charset="UTF8")
        except kinterbasdb.OperationalError as ex:
            raise SqlmapConnectionException(getSafeExString(ex))

        self.initCursor()
        self.printConnected()
Пример #23
0
    def connect(self):
        self.initConnection()

        if not self.hostname:
            self.checkFileDb()

        try:
            # Reference: http://www.daniweb.com/forums/thread248499.html
            self.connector = kinterbasdb.connect(host=self.hostname.encode(UNICODE_ENCODING), database=self.db.encode(UNICODE_ENCODING), user=self.user.encode(UNICODE_ENCODING), password=self.password.encode(UNICODE_ENCODING), charset="UTF8")
        except kinterbasdb.OperationalError as ex:
            raise SqlmapConnectionException(getSafeExString(ex))

        self.initCursor()
        self.printConnected()
Пример #24
0
def test_fb():
    cn = kinterbasdb.connect(dsn=DBNAME,
                             user=DBUSER,
                             password=DBPASS,
                             charset=DBCHAR)
    cur = cn.cursor()
    cur.execute('''insert into ttest (id, c1, c2) values (3, 'xyz', 'abc');''')
    cur.execute('''insert into ttest (id, c1, c2) values (3, 'abc', 'xyz');''')
    cur.execute('''insert into ttest (id, c1, c2) values (3, 'bbb', 'aaa');''')
    cn.commit()
    cur.execute('''select * from ttest;''')
    for row in cur.fetchall():
        print row
    cur.close()
    cn.close()
Пример #25
0
    def Connect(self):

        # Считываем параметры соединения из текстовых полей вкладки Настройки    
        user  = str(self.lineEdit_2.text())
        passw = str(self.lineEdit_3.text())
        path  = str(self.lineEdit.text())

        try: 
         # Подключаемся к базе
         con = kinterbasdb.connect(dsn=path, user=user,  password=passw)
        except:  
         self.lineEdit_4.setText(u"Не удалось подключиться к базе ")
         return False
        self.label_2.setText(u"Подключено")
        self.lineEdit_4.setText(u"Подключение к avto_db удалось.")
        return con
def execute():
    source_id = 'ics.db'
    # logger
    logging.config.dictConfig(settings.LOG_CONF)
    root_logger = logging.getLogger('stat_ics_db_collector.entry_point')
    # source
    ics_db_conn_str = settings.ICS_DB_CONN_STR
    prepared_conn_str = dict(map(lambda k: (k, str(ics_db_conn_str[k])), ics_db_conn_str))
    source_connect_factory = lambda: kinterbasdb.connect(**prepared_conn_str)
    # dest
    dest_db_conn_str = settings.DEST_DB_CONN_STR
    dest_storage = SqliteStorage(dest_db_conn_str, root_logger.getChild('dest_storage'))
    # collect_task
    collect_task_list = collect_task_def.collect_task_def
    # db source collect task
    task = DbSourceCollectTask(source_id, collect_task_list, source_connect_factory, dest_storage, root_logger)
    return task.execute()
Пример #27
0
def _connect():
    global con, work_time, thTimeOut
    work_time = time.time();
    if not con or con.closed:
        if DEBUG_LEVEL > 0:
            Log("Connect to DB:\t%s" % DB_PATH)
        try:
            lcTimeOut.acquire()
            con = fb.connect(dsn=DB_PATH, user=DB_USER, password=DB_PASSWD)
            lcTimeOut.release()
            if not thTimeOut.is_alive():
                thTimeOut = threading.Thread(target=chTimeOut, name="chTimeOut")
                thTimeOut.start()
        except Exception as e:
            if type(e) == fb.OperationalError:
                Log("Connect DataBase:\t%s" % e[1], True)
            else:
                Log("Connect:\t%s" % e, True)
            raise
Пример #28
0
    def _cursor(self):
        new_connection = False
        
        if self.connection is None:
            new_connection = True
            self.connection = Database.connect(**self.settings)
            connection_created.send(sender=self.__class__)
             
        cursor = self.connection.cursor()
        
        if new_connection:
            if self.connection.charset == 'UTF8':
                self.ops.FB_CHARSET_CODE = 4 # UTF-8 with Firebird 2.0+

            self.connection.set_type_trans_in({
                'DATE':             self.ops.conv_in_date,
                'TIME':             self.ops.conv_in_time,
                'TIMESTAMP':        self.ops.conv_in_timestamp,
                'FIXED':            self.ops.conv_in_fixed,
                'TEXT':             self.ops.conv_in_ascii,
                'TEXT_UNICODE':     self.ops.conv_in_unicode,
                'BLOB':             self.ops.conv_in_blob
            })
            self.connection.set_type_trans_out({
                'DATE':             typeconv_datetime.date_conv_out,
                'TIME':             typeconv_datetime.time_conv_out,
                'TIMESTAMP':        typeconv_datetime.timestamp_conv_out,
                'FIXED':            typeconv_fixeddecimal.fixed_conv_out_precise,
                'TEXT':             self.ops.conv_out_ascii,
                'TEXT_UNICODE':     typeconv_textunicode.unicode_conv_out,
                'BLOB':             self.ops.conv_out_blob
            })
            
            version = re.search(r'\s(\d{1,2})\.(\d{1,2})', self.connection.server_version)
            self.server_version = tuple([int(x) for x in version.groups()])
            
            # feature for Firebird version 2 and above
            if self.server_version[0] >=2:
                self.features.can_return_id_from_insert = True
        
        return CursorWrapper(cursor)
Пример #29
0
    def _cursor(self):
        if self.connection is None:
            settings_dict = self.settings_dict
            if settings_dict["NAME"] == "":
                from django.core.exceptions import ImproperlyConfigured

                raise ImproperlyConfigured("You need to specify DATABASE_NAME in your Django settings file.")
            conn_params = {"charset": "UNICODE_FSS"}
            conn_params["dsn"] = settings_dict["NAME"]
            if settings_dict["HOST"]:
                conn_params["dsn"] = ("%s:%s") % (settings_dict["HOST"], conn_params["dsn"])
            if settings_dict["PORT"]:
                conn_params["port"] = settings_dict["PORT"]
            if settings_dict["USER"]:
                conn_params["user"] = settings_dict["USER"]
            if settings_dict["PASSWORD"]:
                conn_params["password"] = settings_dict["PASSWORD"]
            conn_params.update(settings_dict["OPTIONS"])
            self.connection = Database.connect(**conn_params)
            self._type_translator.set_charset(self.connection.charset)
        return FirebirdCursorWrapper(self.connection.cursor(), self._type_translator)
Пример #30
0
    def __init__(self,
                 ui,
                 filename=None,
                 dsn=None,
                 host=None,
                 user="******",
                 pwd="masterkey"):
        SqlConnection.__init__(self, ui)
        self.dbapi = kinterbasdb
        self._user = user
        self._pwd = pwd
        if dsn is not None:
            assert host is None
            assert filename is None
            host, filename = dsn.split(':', 1)
        self._host = host

        if filename is None:
            self._filename = r"c:\temp\tmp.fdb"
            self._host = "localhost"
            if os.path.exists(self._filename):
                os.remove(self._filename)
        else:
            self._filename = filename
            if os.path.exists(filename):
                self._mtime = os.stat(filename).st_mtime

            self._status = self.CST_OPENED
            self._dbconn = kinterbasdb.connect(host=self._host,
                                               database=filename,
                                               user=self._user,
                                               password=self._pwd)
            self.setup_connection()
            return

        self._mtime = 0.0
        self._dbconn = kinterbasdb.create_database(
            "create database '%s:%s' user '%s' password '%s'" %
            (self._host, self._filename, self._user, self._pwd))
        self.setup_connection()
Пример #31
0
 def __init__(self,ui,
              filename=None, dsn=None, host=None,
              user="******",pwd="masterkey"):
     SqlConnection.__init__(self,ui)
     self.dbapi = kinterbasdb
     self._user=user
     self._pwd=pwd
     if dsn is not None:
         assert host is None
         assert filename is None
         host,filename=dsn.split(':',1)
     self._host=host
     
     if filename is None:
         self._filename=r"c:\temp\tmp.fdb"
         self._host="localhost"
         if os.path.exists(self._filename):
             os.remove(self._filename)
     else:
         self._filename = filename
         if os.path.exists(filename):
             self._mtime = os.stat(filename).st_mtime
             
         self._status = self.CST_OPENED
         self._dbconn = kinterbasdb.connect(
             host=self._host,
             database=filename,
             user=self._user,
             password=self._pwd)
         self.setup_connection()
         return
     
     
     self._mtime = 0.0
     self._dbconn = kinterbasdb.create_database(
     "create database '%s:%s' user '%s' password '%s'" % (
         self._host,self._filename,
         self._user,self._pwd))
     self.setup_connection()
Пример #32
0
def getConnection(connUser):
    """
    Returns a database connection as defined by 
    connUser. If this module already has an open
    connection for connUser, it returns it; otherwise,
    it creates a new connection, stores it, and returns it.
    """

    if not _users.has_key(connUser):
        raise SkunkStandardError, 'user %s is not initialized' % (connUser)

    connectParams=_users[connUser]
    
    if not _connections.has_key(connUser):
        try:
			_connections[connUser] = kinterbasdb.connect(**connectParams)           
        except kinterbasdb.Error:
            # XXX Do not raise the connect string! The trace may be seen
            # by users!!!
            raise SkunkStandardError, ('cannot connect to Firebird: %s' % 
                  (sys.exc_info()[1],))

    return _connections[connUser]
Пример #33
0
    def PegaListadoBanco(self):
        '''
        Pega os dados do banco de dados e salva na listaProdutos
        '''

        try:
            conn = kinterbasdb.connect(host="10.1.1.10",
                                       database='C:\SIACPlus\siacCX.fdb',
                                       user="******",
                                       password="******",
                                       charset="ISO8859_1")
            print "Conexão aberta"
            cur = conn.cursor()
            cur.execute(
                'SELECT a.COD_PRODUTO, a.DESCRICAO, a.CODBARRAS, a.SALDOESTOQUE FROM ACADPROD a'
            )
            print "Select executado"
            #print "Lista de Produtos: ", self.listadeProdutos
            # Pegando dados do select e salvando em lista produtos, no momento salvando com estoque zero

            for i in cur:

                (cod_prod, descr, codbarras, saldoestoque) = i

                self.adicionaProdutos(cod_prod, descr, codbarras, saldoestoque)

            print "Produtos adicionados a lista"

            # Fechando acesso ao banco
            conn.close()
            print "Conexão fechada"

        except:
            print "Erro ao acessar o banco"
        finally:
            print "Dados salvo com sucesso"
Пример #34
0
    def __init__(self, **kw):
        """
        This constructor supports all those key word parameters the
        kinterbas.connect() function supports:

        For details on any of these parameters see
        U{http://kinterbasdb.sourceforge.net/dist_docs/usage.html#tutorial_connect}
        
        @param dsn: A DSN pointing to the desired database
        @param user: Username
        @param password: The corresponding password
        @param host: The database host (if no DSN given)
        @param database: The database path (if no DSN given)
        @param charset: Charset for this connection. Unicode strings will be
            uncoding using this charset before they are sent to the database.
            Note that this requires a backend encoding name (see
            U{this site <http://www.firebirdsql.org/index.php?op=doc&id=fb_1_5_charsets&nosb=1>} for details.
        @param dialect: Chose the SQL dialect to use. This doesn't influence
           anything orm does (up to now).
       """
        orm2.datasource.datasource_base.__init__(self)
        self._connection_spec = kw
        self._conn = kinterbasdb.connect(**kw)
        self._update_cursor = self._conn.cursor()
Пример #35
0
    def doFirebird(self):
        global strSelect1, strSelect2, strInsertT1, strInsertT2
        import kinterbasdb

        self.dbms = 'firebird'
        print kinterbasdb.paramstyle
        
        info = conn_info['firebird']
        self.conn = kinterbasdb.connect(
            dsn='localhost:%s' % info['dbname'],
            user = info['user'], 
            password = info['pass'])
        self.cursor = self.conn.cursor()

        strSelect1 = strSelect1.replace("%s", "?")
        strSelect2 = strSelect2.replace("%s", "?")
        strInsertT1 = strInsertT1.replace("%s", "?")
        strInsertT2 = strInsertT2.replace("%s", "?")

        self.doTests()
        strSelect1 = strSelect1.replace("?", "%s")
        strSelect2 = strSelect2.replace("?", "%s")
        strInsertT1 = strInsertT1.replace("?", "%s")
        strInsertT2 = strInsertT2.replace("?", "%s")
Пример #36
0
    def __init__(self, **kw):
        """
        This constructor supports all those key word parameters the
        kinterbas.connect() function supports:

        For details on any of these parameters see
        U{http://kinterbasdb.sourceforge.net/dist_docs/usage.html#tutorial_connect}
        
        @param dsn: A DSN pointing to the desired database
        @param user: Username
        @param password: The corresponding password
        @param host: The database host (if no DSN given)
        @param database: The database path (if no DSN given)
        @param charset: Charset for this connection. Unicode strings will be
            uncoding using this charset before they are sent to the database.
            Note that this requires a backend encoding name (see
            U{this site <http://www.firebirdsql.org/index.php?op=doc&id=fb_1_5_charsets&nosb=1>} for details.
        @param dialect: Chose the SQL dialect to use. This doesn't influence
           anything orm does (up to now).
       """
        orm2.datasource.datasource_base.__init__(self)
        self._connection_spec = kw
        self._conn = kinterbasdb.connect(**kw)
        self._update_cursor = self._conn.cursor()
Пример #37
0
cfg = {}
cfg['dsn'] = cfg_json['firebird']['dsn'].encode('latin-1')
cfg['usr'] = cfg_json['firebird']['usr'].encode('latin-1')
cfg['psw'] = cfg_json['firebird']['psw'].encode('latin-1')

info = {}
info['data_ini'] = cfg_json['datas']['ini'].encode('latin-1')
info['data_fin'] = cfg_json['datas']['fin'].encode('latin-1')

sefaz_doc = '' 

print "Configurações carregadas"

# Conecta ao BD
print "Conectado ao banco de dados..."

con = kinterbasdb.connect(dsn=cfg['dsn'], user=cfg['usr'], password=cfg['psw'])

print "Conexão estabelecida"

# Bloco 0
# Linha 0000
print "Gerando Bloco 0..."

l_0000 = open('templates/0000.txt').read();
l_0000 = l_0000.replace("{@data_inicial}",  info['data_ini']).replace('/', '')
l_0000 = l_0000.replace("{@data_final}",    info['data_fin']).replace('/', '')

print l_0000
Пример #38
0
import DNS
import kinterbasdb

DNS.AddNameServer('172.16.0.4')

r = DNS.Request()

con = kinterbasdb.connect(dsn="spider:/var/ib/swamp_test.gdb",
                          user="******",
                          password="******")

cur = con.cursor()

query = """
select * from s_computers
"""

cur.execute(query)
for i in cur.fetchall():
    name = i[4].lower()
    res = r.req('%s.swamp.lan' % name, qtype='A')
    if len(res.answers):
        print "%s\t%s" % (name, res.answers[0]['data'])
        pass
    else:
        print "%s [not found]" % name
Пример #39
0
	def connect(self):
		self.con = kinterbasdb.connect(dsn='/home/gustavo/Documentos/LG3_7_TRS.FDB', user='******', password='******')
Пример #40
0
def main():

    # get date
    print "\n\
  +------------------------------------------+\n\
  |                                          |\n\
  |       MKU -> BIOS                        |\n\
  |                                          |\n\
  +------------------------------------------+\n\
\n"

    print " DATE  (01-31): ",
    rw_date = int(sys.stdin.readline(10))

    print "MONTH (01-12): ",
    rw_month = int(sys.stdin.readline(10))

    print "GOD   (200?) : ",
    rw_year = int(sys.stdin.readline(10))

    print rw_year, "-", rw_month, "-", rw_date

    # create firebird connection
    con = fb.connect(dsn='%s:%s' % (FB_HOST, FB_DB),
                     user=FB_USER,
                     password=FB_PASS)
    cur = con.cursor()
    # query
    cur.execute("select number, rwdate, wei, pos, cert, a from vagons\
	             where a is not null and wei is not null and\
	             pos is not null and cert is not null and number is not null and\
	             rwdate='%4d-%2d-%2d'" % (rw_year, rw_month, rw_date))

    # create new dbf
    dn = dbf_new()
    dn.add_field("N_VAG", 'C', 8)
    dn.add_field("DATA", 'D', 8)
    dn.add_field("KOL_R", 'N', 8, 2)
    dn.add_field("N_POZ", 'C', 7)
    dn.add_field("N_UD", 'C', 5)
    dn.add_field("AN_ZOL", 'N', 5, 2)
    dn.write(DBF_FILE)

    d = Dbf()
    d.openFile(DBF_FILE, readOnly=0)
    #d.reportOn()
    print

    for row in cur:
        #print row
        # add a record

        rec = DbfRecord(d)
        rec['N_VAG'] = str(row[0])
        rec['DATA'] = row[1].timetuple()
        rec['KOL_R'] = float(row[2])
        rec['N_POZ'] = "% 7s" % str(row[3])
        rec['N_UD'] = "% 5s" % str(row[4])
        rec['AN_ZOL'] = float(row[5])
        rec.store()

        #print row[0], row[1], row[2], row[3], row[4], row[5]
        print rec['N_VAG'], rec['DATA'], rec['KOL_R'], rec['N_POZ'], rec[
            'N_UD'], rec['AN_ZOL']

    print "Records exported: ", d.recordCount()
    print
    d.close()

    # save to floppy
    print "Insert disk in floppy drive and press enter"
    sys.stdin.readline()

    copyfile(DBF_FILE, "c://%s" % DBF_FILE)

    print "Ready"

    time.sleep(3)
Пример #41
0
#importamos a lib de acesso
import kinterbasdb
#instalar o driver - download firebirdsql.org

#conectamos ao banco de dados
con = kinterbasdb.connect(dsn='localhost:c:/meubanco.fdb',
                          user='******',
                          password='******')

#buscamos o cursor
cursor = con.cursor()

#select para listar o nome de todos os clientes cadastrados
sql = 'SELECT NOME FROM CLIENTES ORDER BY NOME'

#executamos o select
cursor.execute(sql)

#percorremos todos os registros mostrando o nome retornado
for pessoa in cursor.fetchall():
    print pessoa[0]
    #o índice aqui refere-se ao campo retornado. Como somente retornamos o nome existe apenas um campo retornado. O índice começa em zero.
    #se o select retornasse mais dados, como NOME, ENDERECO, TELEFONE, por exemplo, o endereco seria pessoa[1] e o telefone pessoa[2]

#depois de retornarmos os dados, fechamos a conexão
con.close()
Пример #42
0
#!/usr/bin/python

#coding: utf-8

import kinterbasdb

con = kinterbasdb.connect(dsn='localhost:temp/cds.fdb', user='******', password='******')

cur = con.cursor()

sql = "create table cds("\
"nome varchar(20),"\
"artista varchar(20)"\
"ano integer, "\
"faixas integer,"\
"primary key(nome, artista, ano));"

#cria uma tabela
cur.execute(sql)

con.commit()

dados = [
   ('IV', 'Led Zeppelin', 1971, 8),
   ('Zenyatta Mondatta', 'The Police', 1980, 11),
   ('OK Computer', 'Radio Head', 1997, 12),
   ('In Absentia', 'Porcupine Tree', 2002, 12),
]

#insere resultados e faz interpolacao
insert = "insert into cds"\
Пример #43
0
import kinterbasdb

# The server is named 'bison'; the database file is at '/temp/test.db'.
con = kinterbasdb.connect(dsn='bison:/temp/test.db',
                          user='******',
                          password='******')

# Or, equivalently:
con = kinterbasdb.connect(host='bison',
                          database='/temp/test.db',
                          user='******',
                          password='******')
Пример #44
0
# SQlite
con2 = sqlite.connect('nome do arquivo', mode=775) # mode define o modo de trabalho

# PostgreSQL
con3 = PgSQL.connect(
    host = 'servidor',
    database = 'banco de dados',
    user = '******'
    password = '******'
)

# Interbase / Firebird
con4 = kinterbasdb.connect(
    dsn = 'servidor:/path/arquivo.fdb',
    user = '******',
    password = '******'
)

# MS-SQL
con5 = pymssql.connect(
    host = 'servidor',
    user = '******',
    password = '******',
    database = 'base de dados' # nome do banco
)

# Oracle database
con6 = cx_Oracle.connect('usuario/senha@tnsname')

Пример #45
0
		self.State='COMPLIT'
		newState='END'
		return (newState, val)
		
	def error(self,val):
		self.db.rollback()
		print 'ERROR'
		self.State='ERROR'
		newState='End'
		return (newState, val)
		
	def create_state(self,m):
		m.add_state('READ_LINE', self.get_line) #, 'TERM','EXT_TERM','COMMIT','SKIP'
		m.add_state('CLEAN_REM', self.clean_leades_rem)
		m.add_state('TERM', self.get_term)
		m.add_state('EX_TERM', self.get_ex_term)
		m.add_state('EXEC_SQL',self.exec_SQL)
		m.add_state('COMMIT',self.commit)
		m.add_state('ERROR',self.error)
		m.add_state('END',None,end_state=1)
		m.set_start('READ_LINE')
        

if __name__== "__main__":
	mydb=kdb.connect(dsn='platon_svn',user='******', password='******',dialect=3, charset='UTF8' )
	input_file=os.path.dirname(__file__)+'\\indexer.sql'
	output_file=os.path.dirname(__file__)+'\\out.sql'
	parser=ParserScript(mydb,input_file,output_file)
	parser.run()
	print parser.State
Пример #46
0
    t2 = time.time()
    cur.execute("select * from test where date_ins between 17250101 and 17441231")
    t3 = time.time()
    print "Tempo estrazione dati dal 01/01/1725 al 31/12/1744: %f" % (t3 - t2)

    t4 = time.time()
    cur.execute("select * from test where date_ins between 17250101 and 18241231")
    t5 = time.time()
    print  "Tempo estrazione dati dal 01/01/1725 al 31/12/1824 %f" % (t5 - t4)

    t6 = time.time()
    cur.execute("select * from test where date_ins between 17250101 and 19241231")
    t7 = time.time()
    print "Tempo estrazione dati dal 01/01/1725 al 31/12/1924 %f" % (t7 - t6)

    cur.close()

if __name__ == "__main__":
    print "Inizio test"
    con = db.connect(host="localhost", database="test.fdb",
                 user="******", password="******")

    print "Inserimento dati"
    insert_data(con.cursor())

    print "Esecuzione query"
    query_data(con.cursor())

    print "Fine test"
    con.close()
Пример #47
0
 def _destroy_test_db(self, test_database_name, verbosity):
     connection = Database.connect(**self._get_connection_params(database=test_database_name))
     connection.drop_database()
     connection.close()
Пример #48
0
import DNS
import kinterbasdb

DNS.AddNameServer('172.16.0.4')

r=DNS.Request()


con = kinterbasdb.connect(
	dsn="spider:/var/ib/swamp_test.gdb",
	user="******",
	password="******"
	)

cur = con.cursor()


query = """
select * from s_computers
"""

cur.execute(query)
for i in cur.fetchall():
	name = i[4].lower()
	res = r.req('%s.swamp.lan' % name ,qtype='A')
	if len(res.answers):
		print "%s\t%s" % (name, res.answers[0]['data'])
		pass
	else:
		print "%s [not found]" % name
Пример #49
0
 def connect(self):
     self._db = kinterbasdb.connect(dsn=self._bdd,
                                    user=self._user,
                                    password=self._password,
                                    charset=self._charset)
Пример #50
0
    from pysqlite2 import dbapi2 as sqlite
    
    con = sqlite.connect('adoradores.sqlite')

    version = FullVersionBuilder(SQLite, connection=con, version_number=1)
    version.export_to_file('version1.py')

if CASE_4:
    print 'Full Version generating from Firebird database...'

    import kinterbasdb
    
    con = kinterbasdb.connect(
            host='localhost',
            database='phonus',
            user='******',
            password='******',
            dialect=3,
            charset='ISO88591',
            )

    version = FullVersionBuilder(Firebird, connection=con, version_number=1)
    version.export_to_file('version1.py')

if CASE_5:
    print 'Parsing:', versions_path

    import kinterbasdb
    
    con = kinterbasdb.connect(
            host='localhost',
            database='phonus_teste',
Пример #51
0
 def connect(self):
     if self.dbObject != None:
         raise Exception("Firebird: already connected to %s" % self.db)
     self.dbObject = kinterbasdb.connect(dsn=self.db, user=self.user, password=self.password, charset=self.charset)