Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: Zeroql en 27 Julio 2010, 04:34 am



Título: ADO y vb.net
Publicado por: Zeroql en 27 Julio 2010, 04:34 am
Buenas
bueno la verdad es k no hace mucho me pase a .net, no he tenido problemas con algunos codigos, y estoy muy nuevo en realizar conexiones con ADO.

Sucede lo sig, en 6.0 yo realizaba una funcion para abrir una base de datos solo la conexion, en .net he visto que tengo que agregar una consulta y la conexion, ademas que todos los manuales y ejemplos que he visto me enredas mas....

y aqui va mis inquietudes.

1. tengo el siguiente code:
Código
  1. Dim strCN As String
  2.        If CFG.isLocalServer = True Then
  3.            strCn = "Data Source=" & CFG.ServerSQL & "; Initial catalog=" & CFG.nameDB & ";Integrated Security=True;Pooling=True"
  4.        Else
  5.            'Se debe indicar el nombre o ip del server en Data Source
  6.            strCN = "Data Source=" & CFG.ServerSQL & "; Initial catalog=" & CFG.nameDB & "; User Id = " & CFG.UserSQL & "; Password = " & CFG.PassSQL
  7.        End If
  8.        Try
  9.            CN = New SqlDataAdapter(Nothing, strCN)
  10.            Return (True)
  11.        Catch exSQL As SqlException
  12.            MsgBox("Error: " & exSQL.Number & vbNewLine & exSQL.Message, MsgBoxStyle.Critical, "Error!")
  13.            Return False
  14.        End Try
  15.    End Function

bueno la cadena esta bien, pero al crear la conexion ¿El
Código
  1. Nothing
no generara error?

2. si alguien tiene un code de conexion solo para conectar y no para consultar, por favor divulgenlo aca.

3. y si alguien conoce un manual para principiantes en ado o ilustrativo y lo publique les he de agradecer...
muchas gracias de ante mano


Título: Re: ADO y vb.net
Publicado por: seba123neo en 27 Julio 2010, 04:44 am
Zeroql.

si solo queres conectarte solamente tenes que hacer...

Código
  1.            Dim vConeccion As New SqlConnection(pCadena)
  2.            vConeccion.Open()

pues en la pagina de el guille es la mejor, esta lleno de ejemplos basicos, tiene todo lo que sea ADO.NET

saludos.


Título: Re: ADO y vb.net
Publicado por: Zeroql en 27 Julio 2010, 04:50 am
Viendo este code que me presentas, no veo tanta la diferencia con el ado de 6.0

Muchas gracias por la colaboracion, funciono de maravilla.

me imagino que para hacer la consulta a la tabla es normal

RS as new  sqlCommand("SELECT * FROM ...)
no

y gracias por lo del guille ahi estuve buscando un ratico, vi algo pero pense que era de 6.0.
gracias.


Título: Re: ADO y vb.net
Publicado por: seba123neo en 27 Julio 2010, 04:57 am
claro, si en realidad es parecido, obvio tiene mas propiedades y demas...pero es parecido.


Título: Re: ADO y vb.net
Publicado por: Zeroql en 27 Julio 2010, 04:58 am
Ok muchas gracias por la info


Título: Re: ADO y vb.net
Publicado por: [D4N93R] en 27 Julio 2010, 15:26 pm
Zeroql, para ser, digamos, nuevo en .Net, veo que tienes buen orden en tu código y captas muy bien las respuestas que se te dan. Veo un buen usuario Experto en .Net acercándose!

Ah se me olvidaba!, las cadenas de conexión las puedes meter en el Web Config.. a mi me gusta más xD


Título: Re: ADO y vb.net
Publicado por: Zeroql en 27 Julio 2010, 17:53 pm
Jejeje graicas D4N93R, me siento alagado, pero debo decir que eso lo parendi al programar en vb 6.0 donde no existe jerarquia y un manejador de errores muy eficiente...
Bueno la web Config no la he manejado aun... xD

Pero buneo, señores necesito otra colaboracion con la siguiente cadena para una conexion a una base de datos access, mmm nose que tengo mal o que carajos sucede con esto: y dice lo siguiente
Código
  1. Public CNAcess As OleDbConnection
  2.  
  3. 'Abrir la base de datos de acceso
  4. Public Function OpenAccess() As Boolean
  5.     Dim strCN As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & My.Application.Info.DirectoryPath & "\Data\UsrAcs.mdb" & ";Persist Security Info=True; Password=" & cfg.DBACSPASS
  6.     Try
  7.          CNAcess = New OleDbConnection(strCN)
  8.          CNAcess.Open()
  9.          Return (True)
  10.    Catch exOleDb As OleDbException
  11.          MsgBox("Error: " & exOleDb.ErrorCode & vbNewLine & exOleDb.Message, MsgBoxStyle.Critical, "Error!")
  12.          Return (False)
  13.    End Try
  14. End Function

al intentar correr este modulo me sale el siguiente error:

No se puede iniciar la aplicación. Falta el archivo de información del grupo de trabajo o bien está abierto en modo exclusivo por otro usuario.

y hasta donde yo se  no tengo abierta la base de datos, me pueden decir como soluciono este inconveniente???


Título: Re: ADO y vb.net
Publicado por: BlackZeroX en 27 Julio 2010, 18:12 pm
.
Te dejo mi modulo de clase seguro te sirve, lo cree cuando estaba trabajando en una chorrada qué se podía optimizar Exasperada-mente para los qué ya estaban... pero qué hacia un proceso X por qué los demás querían gastarle al HD en lugar de hacerlo por Memoria ya qué el resultado tenia qué ser actualizado!¡. (Ya no lo querían Re-Hacer y ponían Demasiados peros xP espero no seas así!¡.)...


OJO: Esta diseñado para trabajar con Hilos, y esta de forma PRE para MySQL!¡.

CLS_Ado.vb

Código
  1.  
  2. Option Explicit On
  3.  
  4. Imports MySql.Data.MySqlClient
  5.  
  6. Public Class Cls_Ado
  7.  
  8.    '   //  Constantes de conexión a MySQL por ADO .NET!¡.
  9.    Private Const PreStrConexion As String = "Server=(ip);Database=(db);user id=(u);password=(p);Connect Timeout=30;"
  10.    Private Const PREDBIpServer As String = "localhost"                 '   //  Predeterminado Default
  11.    Private Const PREDBUser As String = "root"                          '   //  Predeterminado Default
  12.    Private Const PREDBPass As String = "PYP" '"argetniPYP123"          '   //  Predeterminado Default
  13.    Private Const PREDBIni As String = "information_schema"             '   //  Predeterminado Default
  14.  
  15.    '   //  Otros.
  16.    Private StrConexion As String
  17.    Private MySQLConnectionString As String
  18.  
  19.    '   //  .||.
  20.    Private MyDataAdapter As MySqlDataAdapter
  21.    Private MyCommandBuilder As MySqlCommandBuilder
  22.  
  23.    '   //  .||.
  24.    Private DBIpServer As String
  25.    Private DBUser As String
  26.    Private DBPass As String
  27.    Private DBIni As String
  28.  
  29.    Private PrivDataSet As DataSet
  30.    Private PrivSqlQuery As String
  31.    Private PrivTable As String
  32.    Private PrivThisTheardTag As String
  33.  
  34.    Event ErrorEvent(ByVal Ex As Exception, ByVal Cancel As Boolean)
  35.    Event Finish()
  36.  
  37.    Public Property StringConection() As String
  38.        Get
  39.            Return StrConexion
  40.        End Get
  41.        Set(ByVal value As String)
  42.            StrConexion = value
  43.        End Set
  44.    End Property
  45.  
  46.    Public Property This_Theard_Tag() As String
  47.        Get
  48.            Return PrivThisTheardTag
  49.        End Get
  50.        Set(ByVal value As String)
  51.            PrivThisTheardTag = value
  52.        End Set
  53.    End Property
  54.  
  55.    Public Property ServerIP() As String
  56.        Get
  57.            Return DBIpServer
  58.        End Get
  59.        Set(ByVal value As String)
  60.            DBIpServer = value
  61.        End Set
  62.    End Property
  63.  
  64.    Public Property ServerDataBase() As String
  65.        Get
  66.            Return DBIni
  67.        End Get
  68.        Set(ByVal value As String)
  69.            DBIni = value
  70.        End Set
  71.    End Property
  72.  
  73.    Public Property ServerPassword() As String
  74.        Get
  75.            Return DBPass
  76.        End Get
  77.        Set(ByVal value As String)
  78.            DBPass = value
  79.        End Set
  80.    End Property
  81.  
  82.    Public Property ServerUserName() As String
  83.        Get
  84.            Return DBUser
  85.        End Get
  86.        Set(ByVal value As String)
  87.            DBUser = value
  88.        End Set
  89.    End Property
  90.  
  91.    Public Function OpenDBMySql(ByVal pServidorIPDNS As String, ByVal pDBuser As String, ByVal pDBPass As String, _
  92.                                 ByVal pBDD As String, ByVal SqlQuery As String, ByVal MySQLConnectionString As String) _
  93.    As MySql.Data.MySqlClient.MySqlConnection
  94.  
  95.        Dim MyADOConnection As MySql.Data.MySqlClient.MySqlConnection
  96.  
  97.        If StrConexion = Nothing And MySQLConnectionString = Nothing Then
  98.            MySQLConnectionString = PreStrConexion
  99.        Else
  100.            If MySQLConnectionString = Nothing Then
  101.                MySQLConnectionString = StrConexion
  102.            End If
  103.        End If
  104.        If pServidorIPDNS = Nothing And DBIpServer = Nothing Then
  105.            pServidorIPDNS = PREDBIpServer
  106.        Else
  107.            If pServidorIPDNS = Nothing Then
  108.                pServidorIPDNS = DBIpServer
  109.            End If
  110.        End If
  111.        If pDBuser = Nothing And DBUser = Nothing Then
  112.            pDBuser = PREDBUser
  113.        Else
  114.            If pDBuser = Nothing Then
  115.                pDBuser = DBUser
  116.            End If
  117.        End If
  118.        If (pDBPass = Nothing And DBPass = Nothing) Then
  119.            pDBPass = PREDBPass
  120.        Else
  121.            If pDBPass = Nothing Then
  122.                pDBPass = DBPass
  123.            End If
  124.        End If
  125.        If pBDD = Nothing And DBIni = Nothing Then
  126.            pBDD = DBDataBaseIni 'PREDBIni
  127.        Else
  128.            If pBDD = Nothing Then
  129.                pBDD = DBIni
  130.            End If
  131.        End If
  132.  
  133.        MySQLConnectionString = MySQLConnectionString.Replace("(ip)", pServidorIPDNS). _
  134.                                Replace("(db)", pBDD).Replace("(u)", pDBuser).Replace("(p)", pDBPass)
  135.  
  136.        If Not MyDataAdapter Is Nothing Then
  137.            MyDataAdapter = Nothing
  138.        End If
  139.        If Not MyCommandBuilder Is Nothing Then
  140.            MyCommandBuilder = Nothing
  141.        End If
  142.  
  143.        Try
  144.            MyADOConnection = New MySql.Data.MySqlClient.MySqlConnection(MySQLConnectionString)
  145.            MyDataAdapter = New MySqlDataAdapter(SqlQuery, MyADOConnection)
  146.            MyCommandBuilder = New MySqlCommandBuilder(MyDataAdapter)
  147.            Return MyADOConnection
  148.        Catch ex As Exception
  149.            Dim Cancel As Boolean
  150.            RaiseEvent ErrorEvent(ex, Cancel)
  151.            Return Nothing
  152.        End Try
  153.  
  154.    End Function
  155.  
  156.    Public Function ExecuteQuery(Optional ByVal SqlQuery As String = "", Optional ByVal Tabla As String = "") As Boolean
  157.        Dim MyComandoMysql As New MySqlCommand
  158.        Dim MyADOConnection As MySql.Data.MySqlClient.MySqlConnection
  159.        If Not SqlQuery = "" Then
  160.            PrivSqlQuery = SqlQuery
  161.        End If
  162.        If Tabla = "" Then
  163.            PrivTable = Tabla
  164.        End If
  165.        MyADOConnection = OpenDBMySql(DBIpServer, DBUser, DBPass, DBIni, PrivSqlQuery, StrConexion)
  166.        If Not MyADOConnection Is Nothing Then
  167.            Try
  168.                MyADOConnection.Open()
  169.                MyComandoMysql.Connection = MyADOConnection
  170.                MyComandoMysql.CommandType = CommandType.Text
  171.                MyComandoMysql.CommandText = PrivSqlQuery
  172.                MyComandoMysql.ExecuteNonQuery()
  173.                MyADOConnection.Close()
  174.                RaiseEvent Finish()
  175.                Return True
  176.            Catch ex As Exception
  177.                Dim Cancel As Boolean
  178.                RaiseEvent ErrorEvent(ex, Cancel)
  179.                Return False
  180.            End Try
  181.        Else
  182.            RaiseEvent Finish()
  183.            Return False
  184.        End If
  185.    End Function
  186.  
  187.    Public Function GetDataSet(Optional ByVal SqlQuery As String = "", Optional ByVal Tabla As String = "") As DataSet
  188.        Dim tmpDataSet As New DataSet
  189.        Dim MyComandoMysql As New MySqlCommand
  190.        Dim MyADOConnection As MySql.Data.MySqlClient.MySqlConnection
  191.        If Not SqlQuery = "" Then
  192.            PrivSqlQuery = SqlQuery
  193.        End If
  194.        If Not Tabla = "" Then
  195.            PrivTable = Tabla
  196.        End If
  197.        MyADOConnection = OpenDBMySql(DBIpServer, DBUser, DBPass, DBIni, PrivSqlQuery, StrConexion)
  198.        If Not MyADOConnection Is Nothing Then
  199.            Try
  200.                MyADOConnection.Open()
  201.                MyComandoMysql.Connection = MyADOConnection
  202.                MyComandoMysql.CommandType = CommandType.Text
  203.                MyComandoMysql.CommandText = PrivSqlQuery
  204.                MyComandoMysql.ExecuteNonQuery()
  205.                MyDataAdapter.Fill(tmpDataSet, PrivTable)
  206.                MyADOConnection.Close()
  207.            Catch ex As Exception
  208.                Dim Cancel As Boolean
  209.                RaiseEvent ErrorEvent(ex, Cancel)
  210.                If Cancel Then
  211.                    RaiseEvent Finish()
  212.                    Return Nothing
  213.                End If
  214.                tmpDataSet = Nothing
  215.            End Try
  216.            PrivDataSet = tmpDataSet
  217.            RaiseEvent Finish()
  218.            Return tmpDataSet
  219.        Else
  220.            RaiseEvent Finish()
  221.            Return Nothing
  222.        End If
  223.    End Function
  224.  
  225.    Public Property This_DataBase() As DataSet
  226.        Get
  227.            Return PrivDataSet
  228.        End Get
  229.        Set(ByVal value As DataSet)
  230.            PrivDataSet = value
  231.        End Set
  232.    End Property
  233.  
  234.    Public Property This_SqlQuery() As String
  235.        Get
  236.            Return PrivSqlQuery
  237.        End Get
  238.        Set(ByVal value As String)
  239.            PrivSqlQuery = value
  240.        End Set
  241.    End Property
  242.  
  243.    Public Property This_Table() As String
  244.        Get
  245.            Return PrivTable
  246.        End Get
  247.        Set(ByVal value As String)
  248.            PrivTable = value
  249.        End Set
  250.    End Property
  251.  
  252.    Public Function UpdateFromDataSet(Optional ByVal pDataSet As DataSet = Nothing, _
  253.                                      Optional ByVal SQLQuery As String = "", _
  254.                                      Optional ByVal Tabla As String = "") _
  255.    As Boolean
  256.  
  257.        If Not pDataSet Is Nothing Then
  258.            PrivDataSet = pDataSet
  259.        End If
  260.        If Not SQLQuery = "" Then
  261.            PrivSqlQuery = SQLQuery
  262.        End If
  263.        If Not Tabla = "" Then
  264.            PrivTable = Tabla
  265.        End If
  266.  
  267.        Dim MyADOConnection As MySql.Data.MySqlClient.MySqlConnection
  268.        MyADOConnection = OpenDBMySql(DBIpServer, DBUser, DBPass, DBIni, PrivSqlQuery, StrConexion)
  269.        If Not MyADOConnection Is Nothing Then
  270.            Try
  271.                MyADOConnection.Open()
  272.                MyDataAdapter.Update(PrivDataSet, PrivTable)
  273.                MyADOConnection.Close()
  274.                RaiseEvent Finish()
  275.                Return True
  276.            Catch ex As Exception
  277.                Dim Cancel As Boolean
  278.                RaiseEvent ErrorEvent(ex, Cancel)
  279.                RaiseEvent Finish()
  280.                Return False
  281.            End Try
  282.        Else
  283.            RaiseEvent Finish()
  284.            Return False
  285.        End If
  286.    End Function
  287.  
  288.    Public Sub New()
  289.  
  290.    End Sub
  291.  
  292. End Class
  293.  
  294.  

P.D.: Se puede Optimizar xP

Sangriento Infierno Lunar!¡.


Título: Re: ADO y vb.net
Publicado por: Zeroql en 27 Julio 2010, 18:48 pm
Jeje, esta muy interesante tu Clase, la estudiare de cerca.... muchas gracias.