Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Crear un DSN de Sistema

219 views
Skip to first unread message

Antonio J.

unread,
Sep 29, 2000, 3:00:00 AM9/29/00
to

Saludos

Para realizar una conexión con una base de datos tengo que tener un DSN de
Sistema, pero tengo que crearlo mediante código, ya que un usuario
normalito, seguramente no tiene ni idea de qué es eso, y mucho menos de
crearlo. Y demostrado está que gran cantidad de usuarios son bastante
negados en esto de la informática.

Así que es necesario crear este DSN mediante código en Visual Basic, pero no
tengo ni idea de cómo hacerlo.
¿Alguien podría ayudarme?

Muchas gracias.


Norman A. Armas

unread,
Sep 29, 2000, 3:00:00 AM9/29/00
to
Para realizar la conexion no es necesario el uso de DSN.
Este articulo te explica como hacerlo para RDO y para ADO.
========================================

Visual Basic Concepts

Establishing a Connection to a Database


RDO
To open a connection, you must supply a connection string with parameters.
Note that a connection is not required by RDO to create an rdoQuery object,
but is required to initially create an rdoResultset object:

Dim cn As New rdoConnection
Dim cnB As New rdoConnection
Const ConnectString = "uid=myname;pwd=mypw;driver={SQLServer};" & _
"server=myserver;database=pubs;dsn=''"

This connect string accesses a specific SQL Server and permits ODBC to open
a connection without a DSN. This is a typical ODBC connect string with all
of the standard arguments.

The next section, in the form's Load event, establishes the type of cursor
driver and the login timeout. By default, RDO uses the rdUseIfNeeded cursor
type, which invokes server-side cursors on SQL Server. This default is
overridden in the example below by specifying rdUseNone. The
rdDriverNoPrompt flag means that the application generates an error if the
user ID and password do not match.

Private Sub Form_Load()
With cn
cn.Connect = ConnectString
cn.LoginTimeout = 10
cn.CursorDriver = rdUseNone
cn.EstablishConnection rdDriverNoPrompt
End With

This second connection performs any client-batch updates:

With cnB
cnB.Connect = ConnectString
cnB.CursorDriver = rdUseClientBatch
cnB.EstablishConnection
End With
End Sub

The last event occurs when the connection operation completes and it handles
any errors that occur when the connection is opened. With it, you can test
to see if the connection worked, and if so, enable any buttons that rely on
an open connection.

Private Sub cn_Connect(ByVal ErrorOccurred As Boolean)
If ErrorOccurred Then
MsgBox "Could not open connection", vbCritical
Else
RunOKFrame.Enabled = True
End If
End Sub

ADO
To establish a database connection in ADO, first create a set of ADO objects
referenced from the ADODB object. These are used later to set specific
properties that open connections and generate resultsets:

Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim cnB As New ADODB.Connection
Dim Qy As New ADODB.Command

The next line creates a connect string, just like the one you created in the
previous RDO example. In both cases, you are using ODBC's "non-DSN"
connection strategy to save time and increase performance:

Const ConnectString = "uid=myname;pwd=mypw;driver={SQL Server};" & _
"server=myserver;database=pubs;dsn=''"
The following declarations initialize the variables used in this example.
(Note the creation of a variant array to hold the resultset):

Dim sql As String
Dim rc As Integer
Dim i As Integer
Dim Changes As Integer
Dim bms() As Variant

Next, open an ADO connection to a database in the Form_Load event. Note that
this code is very similar to the RDO code except that the constants are
prefaced with "ad" rather than "rd". To see all available constants, look at
the ADODB type library.

Note There's no need to specify the prompting behavior since ADO defaults
to "no prompt". If you elect to change this, however, use the ADO Properties
collection to deal with the desired prompt behavior. In RDO, you can set the
behavior using the OpenConnection argument. In ADO, you must set the
Properties ("Prompt") property.

Also, there's no need to specify a cursor driver if you don't want to use
one (such as the RDO CursorDriver = rdUseNone), since ADO defaults to no
cursor driver by default.

Private Sub Form_Load()
With cn
' Establish DSN-less connection
.ConnectString = ConnectString
.ConnectionTimeout = 10
'.Properties("Prompt") = adPromptNever
' This is the default prompting mode in ADO.
.Open
End With
With cnB
.ConnectString = ConnectString
.CursorLocation = adUseClient
.Open
End With
End Sub


----------------------------------------------------------------------------
----
Send feedback to MSDN.Look here for MSDN Online resources. --


--
============================

Saludos...

Norman ;-)


"Antonio J." <ajbm....@planalfa.es> wrote in message
news:#o#Rb4hKAHA.195@cppssbbsa05...

Gustavo Troncoso

unread,
Sep 29, 2000, 3:00:00 AM9/29/00
to
Chécate esta dirección ahi está lo que necesitas
http://www.vbsquare.com/tips/tip427.html
Un saludo desde León Gto México

Antonio J.

unread,
Sep 29, 2000, 3:00:00 AM9/29/00
to
Muchas gracias Norman, pero el caso es que por no sé qué razón, el Provider
que utilizo, que es el MSDASQL, me obliga a crearme un DSN de Sistema para
poder conectarme con el servidor donde está alojada la base de datos.
Y utilizo este Provider porque, por no sé qué razón, es el único que no me
da ningún mensaje de error ni ningún fallo, a pesar de que me debería bastar
con MS Remote, pero no es así. Pienso que será por problemas de drivers,
pero he estado investigando y preguntando y nadie me ha sabido responder,
así que tengo que quedarme con el MSDASQL y hacer el DSN de Sistema.
Pero si puedes aclararme este problema, te lo agradecería, ya que me
quitaría de muchos quebraderos de cabeza. Porque además, tampoco sé por qué
razón, la cadena de conexión que utilizo, sólo me funciona en determinados
equipos, puede ser por tema de drivers, pero no lo sé.

Muchas gracias.

"Norman A. Armas" <NOSPAM...@apolloships.com> escribió en el mensaje
news:#$pEh9hK...@cppssbbsa02.microsoft.com...

Norman A. Armas

unread,
Sep 29, 2000, 3:00:00 AM9/29/00
to
Usa el siguiente ejemplo, el tercero que es el de SQLServer y prueba a ver
si te funciona....


Using a DSN-Less Connection to an ODBC Driver
In the following example, notice that SQL Server and Oracle both have
Server= parameters but Microsoft Access uses DBQ= to specify a database. SQL
Server also specifies an initial catalog to open on the server with the
DATABASE= clause.

' Access ODBC Driver via DSN-Less
con1.Open "PROVIDER=MSDASQL;" & _

"DRIVER={Microsoft Access Driver (*.mdb)};" & _
"DBQ=C:\...\NWind.mdb;" & _
"UID=admin;PWD=;"

' Oracle ODBC Driver
con1.Open "PROVIDER=MSDASQL;" & _

"DRIVER={Microsoft ODBC for Oracle};" & _
"SERVER=MyOracleServer;" & _
"UID=demo;PWD=demo;"

' SQL Server ODBC Driver
con1.Open "PROVIDER=MSDASQL;" & _

"DRIVER={SQL Server};" & _
"SERVER=MySQLServer;DATABASE=pubs;" & _
"UID=sa;PWD=;"
As in the DSN examples, the Provider is specifically enumerated even though
you could rely upon ADO's use of this particular provider by default.

The significant difference in each of the three connection strings is the
DRIVER= syntax. While shared by all three code samples, the content in
between the {} corresponds to the exact syntax of the name of an ODBC Driver
registered in the ODBC Driver Manager.

The other main difference between each data source is the syntax used to
specify the actual database being opened. For Microsoft Access the DBQ
clause is used to provide a path to an actual Microsoft Access .mdb file.
For SQL Server both the server name as well as the database to access within
that server are specified. For Oracle a value that matches the name of a
service specified in the SQL Easy Net utility is specified.

--
============================

Saludos...

Norman ;-)


"Antonio J." <ajbm....@planalfa.es> wrote in message

news:#vu0NUiKAHA.257@cppssbbsa05...

Antonio J.

unread,
Sep 29, 2000, 3:00:00 AM9/29/00
to

Muchas gracias Gustavo. Pero sigo teniendo problemas, a ver si me puedes
ayudar. Please.

Aunque he tenido que cambiar el código al que me has remitido, por fallos en
los driver por parte de Microsoft, por supuesto, me da un fallo que me dice
que una DLL no existe, que es 'odbcinst.dll'.

He copiado la DLL, pero no me deja registrarla.
¿Tengo que copiarla en algún directorio específico?
He probado en C:\WINNT\SYSTEM32 y en C:\ARCHIVOS DE PROGRAMA\ARCHIVOS
COMUNES\SYSTEM\OLE DB.
¿o tengo que instalar algo para que me copie la DLL y me la registre?

Muchas gracias.


"Gustavo Troncoso" <gtro...@cuinba.com> escribió en el mensaje
news:uh5zfIiKAHA.241@cppssbbsa05...


> Chécate esta dirección ahi está lo que necesitas
> http://www.vbsquare.com/tips/tip427.html
> Un saludo desde León Gto México

> Antonio J. <ajbm....@planalfa.es> wrote in message

> news:##Rb4hKAHA.195@cppssbbsa05...

Jorge López

unread,
Sep 29, 2000, 3:00:00 AM9/29/00
to
Espero que esto te ayude aunque a mi me funcionan perfectamente las
conexiones con ADO pasandoles una cadena de conexión y sin utilizar DSNs,
eso si tengo instalado el cliente de SQL server 7.0 en esa máquina.

Saludos

"Este código no es mio lo encontre el otro día en una web pero no me acuerdo
cual"
"Lo he probado con VB 6.0 y ha funcionado"
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------
En la versión 32 bits de VB es posible usar conexiones sin DSN, pero como la
versión de 16 bits del
ODBC no puede manejar esta sintaxis no es posible hacerlo con el VB 4.0 16.
Podemos simularlo
creando y eliminando dinámicamente el DSN empleando la función
SQLConfigDataSource del API de
ODBC.
Los siguientes ejemplos en 16 y 32 bits muestran esta técnica. Se ha
incluído código de 32 bits porque
tiene también otros usos que veremos a continuación. Las técnicas de 32 bits
presentadas pueden
aplicarse también en VB 5.0.

El poder establecer una conexión sin DSN tiene ventajas:
1 - Simplicidad. El usuario no necesita preocuparse de crear el DSN,
nombrarlo correctamente, establecer
sus opciones, etc. Esto lo hace dinámicamente la aplicación.
2 - Incrementa la flexibilidad de la aplicación.

Todo esto puede ser realizado en ODBC de 16 bits creando y eliminando un DSN
dinámicamente. Este
método es útil también para un manejo simple de DSN. Podremos crear,
modificar y eliminar DSNs en
cualquier momento. Visual Basic permite crear un DSN empleando el método
DBEngine.RegisterDatabase, pero el API de ODBC nos da mayor funcionalidad y
la posibilidad de
modificar y eliminar un DSN también.

Declaramos las constantes y funciones necesarias :

'declaracion de constantes
Private Const ODBC_ADD_DSN = 1 ' Add data source
Private Const ODBC_CONFIG_DSN = 2 ' Configure (edit) data source
Private Const ODBC_REMOVE_DSN = 3 ' Remove data source
Private Const vbAPINull As Long = 0& ' NULL Pointer
'delcaracion de funciones
#If Win32 Then
Private Declare Function SQLConfigDataSource Lib "ODBCCP32.DLL" _
(ByVal hwndParent As Long, ByVal fRequest As Long, _
ByVal lpszDriver As String, ByVal lpszAttributes As String) As
Long
#Else
Private Declare Function SQLConfigDataSource Lib "ODBCINST.DLL" _
(ByVal hwndParent As Integer, ByVal fRequest As Integer, ByVal _
lpszDriver As String, ByVal lpszAttributes As String) As Integer
#End If


Para crear un DSN :

#If Win32 Then
Dim intRet As Long
#Else
Dim intRet As Integer
#End If
Dim strDriver As String
Dim strAttributes As String

'usamos el driver de SQL Server porque es el mas comun
strDriver = "SQL Server"
'Asignamos los parametros separados por null.
strAttributes = "SERVER=SomeServer" & Chr$(0)
strAttributes = strAttributes & "DESCRIPTION=Temp DSN" & Chr$(0)
strAttributes = strAttributes & "DSN=DSN_TEMP" & Chr$(0)
strAttributes = strAttributes & "DATABASE=pubs" & Chr$(0)
strAttributes = strAttributes & "UID=sa" & Chr$(0)
strAttributes = strAttributes & "PWD=" & Chr$(0)
'Para mostrar el diálogo usar Form1.Hwnd en vez de vbAPINull.
intRet = SQLConfigDataSource(vbAPINull, ODBC_ADD_DSN, strDriver,
strAttributes)
If intRet Then
MsgBox "DSN Creado"
Else
MsgBox "Fallo en la creación"
End If


Para borrarlo :

#If Win32 Then
Dim intRet As Long
#Else
Dim intRet As Integer
#End If
Dim strDriver As String
Dim strAttributes As String
'usamos el driver de SQL Server porque es el mas comun
strDriver = "SQL Server"
'Asignamos los parametros separados por null.
strAttributes = "DSN=DSN_TEMP" & Chr$(0)
'Para mostrar el diálogo usar Form1.Hwnd en vez de vbAPINull.
intRet = SQLConfigDataSource(vbAPINull, ODBC_REMOVE_DSN, strDriver,
strAttributes)
If intRet Then
MsgBox "DSN Eliminado"
Else
MsgBox "Fallo en el borrado"
End If


Para modificarlo:

#If Win32 Then
Dim intRet As Long
#Else
Dim intRet As Integer
#End If
Dim strDriver As String
Dim strAttributes As String

'usamos el driver de SQL Server porque es el mas comun
strDriver = "SQL Server"
'Asignamos los parametros separados por null.
strAttributes = "SERVER=OtroSomeServer" & Chr$(0)
strAttributes = strAttributes & "DESCRIPTION=Temp DSN modificado" & Chr$(0)
strAttributes = strAttributes & "DSN=DSN_TEMP" & Chr$(0)
strAttributes = strAttributes & "DATABASE=pubs" & Chr$(0)
strAttributes = strAttributes & "UID=sa" & Chr$(0)
strAttributes = strAttributes & "PWD=" & Chr$(0)

'Para mostrar el diálogo usar Form1.Hwnd en vez de vbAPINull.
intRet = SQLConfigDataSource(vbAPINull, ODBC_CONFIG_DSN, strDriver,
strAttributes)
If intRet Then
MsgBox "DSN Modificado"
Else
MsgBox "Fallo en la modificacion"
End If

Nota
Si el DSN es para access hay que tener en cuenta :
- En vez de DATABASE debes usar DBQ y especificar el nombre completo de la
base de datos, incluyendo el path y la extension.

- El UID por defecto es admin, aunque en la base de datos este en español y
se llame administrador.

Si tienes problemas lo mas sencillo es que hagas un dsn de fichero (File
Dsn) y luego con el notepad lo editas y puedes ver los parametros que usa.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------


Gustavo Troncoso

unread,
Sep 29, 2000, 3:00:00 AM9/29/00
to

Bueno no sé si ya intentaste registrar dicha dll con regsvr32.exe aqui no
importa la ubicación de esta dll, pero por costumbre la puedes poner en
system32

Antonio J. <ajbm....@planalfa.es> wrote in message
news:udQ1usiKAHA.195@cppssbbsa05...

Fernando G. Guerrero

unread,
Oct 1, 2000, 3:00:00 AM10/1/00
to

Debes instalar mdac_typ.exe en las máquinas cliente, para asegurarte de que
tienen las últimas librerías instaladas. Puedes conseguir la última versión
(2.6) del programa en:

http://www.microsoft.com/data/download_260rtm.htm

Tal y como han comentado otros compañeros, deberías utilizar conexiones sin
DSN ya que te ofrecen más control desde programa, aunque se pierde
flexibilidad externa. Personalmente prefiero utilizar conexiones sin DSN.

Una cadena de conexión típica podría ser:

Utilizando el proveedor nativo OLEDB para SQL Server:

"Provider=SQLOLEDB;Server=TuServidor;Data Source=TuBase;User
ID=TuLogin;Password=TuPassword;"

Utilizando el proveedor OLEDB para ODBC en conjunto con el driver ODBC para
SQL Server:

"Provider=MSDASQL;Driver={SQL
Server};Server=TuServidor;Database=TuBase;UID=TuLogin;PWD=TuPassword;"

Te recomiendo el primer ejemplo de todos modos, ya que utilizar OLEDB + ODBC
no es muy eficiente.

--
Fernando G. Guerrero
QA Group Ltd., UK
Share what you know, learn what you don't


"Antonio J." <ajbm....@planalfa.es> wrote in message

news:#o#Rb4hKAHA.195@cppssbbsa05...

0 new messages