¿Cuál es la forma más sencilla y fácil de crear para crear una fuente de datos ODBC de SQL Server?

StackOverflow https://stackoverflow.com/questions/170466

Pregunta

Necesito una forma programática de crear una fuente de datos ODBC de SQL Server. Puedo hacer esto accediendo directamente al Registro. Sería mejor si esto pudiera hacerse a través de una API disponible (SQL Server / Windows) para protegerse contra cambios en las claves de registro o valores con controladores de SQL Server actualizados.

Nota de respuesta aceptada: El uso de SQLConfigDataSource abstrae el código de los detalles de las claves de registro, etc., por lo que es más sólido. Sin embargo, esperaba que SQL Server hubiera envuelto esto con una función de nivel superior que tomara atributos fuertemente tipados (en lugar de una cadena delimitada) y la expusiera a través del controlador.

¿Fue útil?

Solución

SQLConfigDataSource () hace el trabajo.

Artículo de MSDN

Por si acaso hay un ejemplo de VB6:

Const ODBC_ADD_DSN = 1 'user data source
Const ODBC_ADD_SYS_DSN = 4 'system data source

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

strDriver = "SQL Server"
strAttributes = "DSN=Sample" & Chr$(0) _
& "Database=Northwind" & Chr$(0) _
& "Description= Sample Data Source" & Chr$(0) _
& "Server=(local)" & Chr$(0) _
& "Trusted_Connection=No" & Chr$(0)

SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, strDriver, strAttributes)

Otros consejos

Para VB.NET se puede hacer de esta manera:

Importar para 'DllImport':

Imports System.Runtime.InteropServices

Declaración de SQLConfigDataSource:

<DllImport("ODBCCP32.DLL")> Shared Function SQLConfigDataSource _
(ByVal hwndParent As Integer, ByVal fRequest As Integer, _
    ByVal lpszDriver As String, _
    ByVal lpszAttributes As String) As Boolean
End Function

Ejemplo de uso:

Const ODBC_ADD_DSN = 1 'User data source
Const ODBC_ADD_SYS_DSN = 4 'System data source

Public Function CreateSqlServerDataSource
    Dim strDriver As String : strDriver = "SQL Server"
    Dim strAttributes As String : strAttributes = _
        "DSN=Sample" & Chr(0) & _
        "Database=Northwind" & Chr(0) & _
        "Description= Sample Data Source" & Chr(0) & _
        "Server=(local)" & Chr(0) & _
        "Trusted_Connection=No" & Chr(0)

    SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, strDriver, strAttributes)
End Function

Usaré odbcad32.exe que se encuentra en la carpeta de su system32.

Esto agregará sus fuentes de datos odbc a la ubicación correcta, lo que no se verá afectado por ningún parche.

Para hacer esto directamente en el registro, puede agregar un valor de cadena a:

HKLM\SOFTWARE\Microsoft\ODBC\ODBC.INI\ODBC Data Sources

para agregar un DSN del sistema, o:

HKCU\Software\ODBC\ODBC.INI\ODBC Data Sources

para agregar un DSN de usuario.

El nombre del valor es el nombre de la fuente de datos que desea crear y los datos deben ser 'SQL Server'.

Al mismo nivel que 'Fuentes de datos ODBC' en el Registro, cree una clave con el nombre de la fuente de datos que desea crear.

Esta clave necesita los siguientes valores de cadena:

Database     - Name of default database to which to connect
Description  - A description of the Data Source
Driver       - C:\WINDOWS\system32\SQLSRV32.dll
LastUser     - Name of a database user (e.g. sa)
Server       - Hostname of machine on which database resides

Por ejemplo, al usar la aplicación reg.exe desde la línea de comandos para agregar una fuente de datos de usuario llamada 'ExampleDSN':

reg add "HKCU\Software\ODBC\ODBC.INI\ODBC Data Sources" 
    /v ExampleDSN /t REG_SZ /d "SQL Server"
reg add HKCU\Software\ODBC\ExampleDSN 
    /v Database /t REG_SZ /d ExampleDSN
reg add HKCU\Software\ODBC\ExampleDSN 
    /v Description /t REG_SZ /d "An Example Data Source"
reg add HKCU\Software\ODBC\ExampleDSN
    /v Driver /t REG_SZ /d "C:\WINDOWS\system32\SQLSRV32.DLL"
reg add HKCU\Software\ODBC\ExampleDSN
    /v LastUser /t REG_SZ /d sa
reg add HKCU\Software\ODBC\ExampleDSN
    /v Server /t REG_SZ /d localhost

Muestra usando C #:

(Referencia detallada de parámetros de SQL Server en http://msdn.microsoft). com / en-us / library / aa177860.aspx )

using System.Runtime.InteropServices; 

        private enum RequestFlags : int
        {

            ODBC_ADD_DSN = 1,
            ODBC_CONFIG_DSN = 2,
            ODBC_REMOVE_DSN = 3,
            ODBC_ADD_SYS_DSN = 4,
            ODBC_CONFIG_SYS_DSN = 5,
            ODBC_REMOVE_SYS_DSN = 6,
            ODBC_REMOVE_DEFAULT_DSN = 7

        }

        [DllImport("ODBCCP32.DLL", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern bool SQLConfigDataSource(UInt32 hwndParent, RequestFlags  fRequest, 
                                 string lpszDriver, string lpszAttributes);

        public static void CreateDSN()
        {

            string strDrivername = "SQL Server";
            string strConfig =  "DSN=StackOverflow\0" +
                                   "Database=Northwind\0" +
                                   "Description=StackOverflow Sample\0" +
                                   "Server=(local)\0" +
                                   "Trusted_Connection=No\0";

            bool success = SQLConfigDataSource(0, RequestFlags.ODBC_ADD_SYS_DSN, strDrivername, strConfig);

        }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top