Banco de dados local usando Valentina ODBC Driver

Exemplo de string de conexão com Valentina usando Valentina ODBC Driver

Exemplo de string de conexão

Essa é uma string de conexão do provider Valentina ODBC Driver para se conectar com Valentina.

Banco de dados local

Driver={Valentina ODBC Driver};IsDatabaseLocal=yes;Database=C:\Diretorio\Arquivo.vdb;

Conexão através de diferentes linguagens

C#

Exemplo de código em C# de conexão com Valentina usando Valentina ODBC Driver:

using System;
using System.Data.Odbc;

class DatabaseConnection {
    static void Main() {
        // Define a string de conexão Valentina usando Valentina ODBC Driver
        string connectionString = "Driver={Valentina ODBC Driver};IsDatabaseLocal=yes;Database=C:\\Diretorio\\Arquivo.vdb;";

        using (OdbcConnection connection = new OdbcConnection(connectionString)) {
            try {
                // Abre a conexão
                connection.Open();

                Console.WriteLine("Conexão aberta com sucesso!");

                //
                // INSIRA SEU CÓDIGO AQUI
                //

            } catch (OdbcException ex) {
                // Erros específicos do OdbcException
                Console.WriteLine("Erro: " + ex.Message);
            } catch (Exception ex) {
                // Outros erros
                Console.WriteLine("Erro: " + ex.Message);            

            } finally {
                // Fecha a conexão
                if (connection != null) {
                    connection.Close();
                    Console.WriteLine("Conexão fechada.");
                }
            }
        }
    }
}

VB.NET

Exemplo de código em VB.NET de conexão com Valentina usando Valentina ODBC Driver:

Imports System
Imports System.Data.Odbc

Module DatabaseConnection

    Sub Main()
        Dim connectionString As String
        
        ' Define a string de conexão Valentina usando Valentina ODBC Driver
        connectionString = "Driver={Valentina ODBC Driver};IsDatabaseLocal=yes;Database=C:\Diretorio\Arquivo.vdb;"

        Using connection As New OdbcConnection(connectionString)
            Try
                ' Abre a conexão
                connection.Open()

                Console.WriteLine("Conexão aberta com sucesso!")

                '
                ' INSIRA SEU CÓDIGO AQUI
                '

            Catch ex As OdbcException
                ' Erros específicos do OdbcException
                Console.WriteLine("Erro: " & ex.Message)
            Catch ex As Exception
                ' Outros erros
                Console.WriteLine("Erro: " & ex.Message)
            Finally
                ' Fecha a conexão
                If connection IsNot Nothing Then
                    connection.Close()
                    Console.WriteLine("Conexão fechada.")
                End If
            End Try


        End Using
    End Sub

End Module

Node.js

Exemplo de código em Node.js de conexão com Valentina usando Valentina ODBC Driver:

const odbc = require('odbc');

// Define a string de conexão Valentina usando Valentina ODBC Driver
const connectionString = 'Driver={Valentina ODBC Driver};IsDatabaseLocal=yes;Database=C:\\Diretorio\\Arquivo.vdb;';

try {
  // Abre a conexão
  odbc.connect(connectionString, (error, connection) => {
    if (error) {
      console.error('Erro:', error.message);
      return;
    }

    console.log('Conexão aberta com sucesso!');

    //
    // INSIRA SEU CÓDIGO AQUI
    //

    // Fecha a conexão
    connection.close((error) => {
      if (error) {
        console.error('Erro ao fechar a conexão:', error.message);
        return;
      }

      console.log('Conexão fechada com sucesso!');
    });
  });
} catch (error) {
  console.error('Erro geral:', error.message);
}

Este código requer que você instale o módulo odbc através do seguinte comando:

npm install odbc

PHP

Exemplo de código em PHP de conexão com Valentina usando Valentina ODBC Driver:

<?php
// Define a string de conexão Valentina usando Valentina ODBC Driver
$connectionString = "Driver={Valentina ODBC Driver};IsDatabaseLocal=yes;Database=C:\\Diretorio\\Arquivo.vdb;";

try {
    // Abre a conexão usando PDO ODBC
    $pdo = new PDO("odbc:" . $connectionString);

    //
    // INSIRA SEU CÓDIGO AQUI
    //

    // Fecha a conexão
    $pdo = null;
} catch (PDOException $e) {
    // Trata erros de conexão ou exceções
    echo "Erro: " . $e->getMessage();
}
?>

Importante: o código acima funciona apenas no PHP para Windows com PDO_ODBC ativado. Para ativar este driver PDO, basta editar o arquivo php.ini e incluir a linha extension=php_pdo_odbc.dll após a linha extension=php_pdo.dll.

Python

Exemplo de código em Python de conexão com Valentina usando Valentina ODBC Driver:

import pyodbc

# Define a string de conexão ODBC para Valentina usando Valentina ODBC Driver
connectionString = "Driver={Valentina ODBC Driver};IsDatabaseLocal=yes;Database=C:\\Diretorio\\Arquivo.vdb;"

try:
    # Abre a conexão
    connection = pyodbc.connect(connectionString)

    print("Conexão aberta com sucesso!")

    #
    # INSIRA SEU CÓDIGO AQUI
    #

except pyodbc.Error as e:
    print("Erro: ", e)

finally:
    # Fecha a conexão
    if connection:
        connection.close()

Este código requer que você instale o módulo pyodbc através do seguinte comando:

pip install pyodbc

ASP Clássico

Exemplo de código em ASP Clássico de conexão com Valentina usando Valentina ODBC Driver:

<%
Dim conn, connectionString

' Cria a string de conexão para Valentina usando Valentina ODBC Driver
connectionString = "Driver={Valentina ODBC Driver};IsDatabaseLocal=yes;Database=C:\Diretorio\Arquivo.vdb;"

Set conn = Server.CreateObject("ADODB.Connection")

' Abre a conexão
On Error Resume Next
conn.Open connectionString

' Verifica se a conexão foi aberta
If conn.State = 1 Then
    Response.Write "Conexão aberta com sucesso!"
    '
    ' INSIRA SEU CÓDIGO AQUI
    '
Else
    If Err.Number <> 0 Then
        Response.Write "Erro: " & Server.HTMLEncode(Err.Description)
    Else
        Response.Write "Erro: A conexão não pode ser estabelecida."
    End If

End If

On Error GoTo 0

' Fecha a conexão
conn.Close
Set conn = Nothing

%>

VBScript

Exemplo de código em VBScript de conexão com Valentina usando Valentina ODBC Driver:

Dim conn, connectionString

' Define a string de conexão Valentina usando Valentina ODBC Driver
connectionString = "Driver={Valentina ODBC Driver};IsDatabaseLocal=yes;Database=C:\Diretorio\Arquivo.vdb;"

Set conn = CreateObject("ADODB.Connection")

' Abre a conexão
On Error Resume Next
conn.Open connectionString

' Verifica se a conexão foi aberta
If conn.State = 1 Then
    Wscript.Echo "Conexão aberta com sucesso!"
    '
    ' INSIRA SEU CÓDIGO AQUI
    '
Else
    If Err.Number <> 0 Then
        WScript.Echo "Erro: " & Err.Description
    Else
        WScript.Echo "Erro: A conexão não pode ser estabelecida."
    End If

End If

On Error GoTo 0

' Fecha a conexão
conn.Close
Set conn = Nothing
Wscript.Echo "Conexão fechada."

JScript

Exemplo de código em JScript de conexão com Valentina usando Valentina ODBC Driver:

var conn, connectionString;

// Define a string de conexão Valentina usando Valentina ODBC Driver
connectionString = "Driver={Valentina ODBC Driver};IsDatabaseLocal=yes;Database=C:\\Diretorio\\Arquivo.vdb;";

conn = new ActiveXObject("ADODB.Connection");

// Abre a conexão
try {
    // Abre a conexão
    conn.Open(connectionString);
    if (conn.State === 1) {
        WScript.Echo("Conexão aberta com sucesso!");
        //
        // INSIRA SEU CÓDIGO AQUI
        //
    } else {
        WScript.Echo("Erro: A conexão não pode ser estabelecida.");
    }
} catch (e) {
    // Exibe a mensagem de erro
    WScript.Echo("Erro: " + e.description);
} finally {
    // Fecha a conexão
    conn.Close();
    conn = null;
}

C++

Exemplo de código em C++ de conexão com Valentina usando Valentina ODBC Driver:

#include <iostream>
#include <cstdlib>
#include <string>
#include <sql.h>
#include <sqlext.h>

int main() {
    // Inicializa o ambiente ODBC
    SQLHENV env = SQL_NULL_HENV;   // Handle do ambiente ODBC
    SQLHDBC dbc = SQL_NULL_HDBC;   // Handle da conexão ODBC
    SQLRETURN ret;                 // Status de retorno ODBC
    SQLWCHAR outstr[1024];         // String de saída para resultados ODBC
    SQLSMALLINT outstrlen;         // Contador de caracteres para resultados ODBC

    // Aloca um ambiente de manipulação ODBC
    ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
    if (ret == SQL_ERROR) {
        std::cout << "Erro ao alocar o ambiente ODBC." << std::endl;
        return EXIT_FAILURE;
    }

    // Define a versão ODBC para a mais recente disponível
    SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);

    // Aloca um handle de conexão
    ret = SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
    if (ret == SQL_ERROR) {
        std::cout << "Erro ao alocar o handle de conexão ODBC." << std::endl;
        SQLFreeHandle(SQL_HANDLE_ENV, env);
        return EXIT_FAILURE;
    }

    // Define a string de conexão Valentina usando Valentina ODBC Driver
    std::wstring connectionString = L"Driver={Valentina ODBC Driver};IsDatabaseLocal=yes;Database=C:\\Diretorio\\Arquivo.vdb;";

    // Tenta conectar usando a string de conexão
    ret = SQLDriverConnectW(dbc, NULL, (SQLWCHAR*)connectionString.c_str(), SQL_NTS, outstr, sizeof(outstr), &outstrlen, SQL_DRIVER_COMPLETE);
    if (SQL_SUCCEEDED(ret)) {
        std::cout << "Conexão aberta com sucesso!" << std::endl;

        //
        // INSIRA SEU CÓDIGO AQUI
        //

        // Desconecta do banco de dados
        SQLDisconnect(dbc);
    } else {
        std::cout << "Falha ao abrir conexão." << std::endl;
    }

    // Libera os handles alocados
    SQLFreeHandle(SQL_HANDLE_DBC, dbc);
    SQLFreeHandle(SQL_HANDLE_ENV, env);

    return EXIT_SUCCESS;
}

Perl

Exemplo de código em Perl de conexão com Valentina usando Valentina ODBC Driver:

use strict;
use warnings;
use DBI;

# Define a string de conexão Valentina usando Valentina ODBC Driver 
my $connection_string = "Driver={Valentina ODBC Driver};IsDatabaseLocal=yes;Database=C:\\Diretorio\\Arquivo.vdb;";

eval {
    # Abre a conexão
    my $dbh = DBI->connect("DBI:ODBC:$connection_string", undef, undef, { PrintError => 0, RaiseError => 1 });
    print "Conexão aberta com sucesso!\n";

    #
    # INSIRA SEU CÓDIGO AQUI
    #

    # Fecha a conexão
    $dbh->disconnect;
};

if ($@) {
    print "Erro: $@\n";
}