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:
Dim strCN As String
If CFG.isLocalServer = True Then
strCn = "Data Source=" & CFG.ServerSQL & "; Initial catalog=" & CFG.nameDB & ";Integrated Security=True;Pooling=True"
Else
'Se debe indicar el nombre o ip del server en Data Source
strCN = "Data Source=" & CFG.ServerSQL & "; Initial catalog=" & CFG.nameDB & "; User Id = " & CFG.UserSQL & "; Password = " & CFG.PassSQL
End If
Try
CN = New SqlDataAdapter(Nothing, strCN)
Return (True)
Catch exSQL As SqlException
MsgBox("Error: " & exSQL.Number & vbNewLine & exSQL.Message, MsgBoxStyle.Critical, "Error!")
Return False
End Try
End Function
bueno la cadena esta bien, pero al crear la conexion ¿El 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
Zeroql.
si solo queres conectarte solamente tenes que hacer...
Dim vConeccion As New SqlConnection(pCadena)
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.
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.
claro, si en realidad es parecido, obvio tiene mas propiedades y demas...pero es parecido.
Ok muchas gracias por la info
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
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
Public CNAcess As OleDbConnection
'Abrir la base de datos de acceso
Public Function OpenAccess() As Boolean
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
Try
CNAcess = New OleDbConnection(strCN)
CNAcess.Open()
Return (True)
Catch exOleDb As OleDbException
MsgBox("Error: " & exOleDb.ErrorCode & vbNewLine & exOleDb.Message, MsgBoxStyle.Critical, "Error!")
Return (False)
End Try
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???
.
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
Option Explicit On
Imports MySql.Data.MySqlClient
Public Class Cls_Ado
' // Constantes de conexión a MySQL por ADO .NET!¡.
Private Const PreStrConexion As String = "Server=(ip);Database=(db);user id=(u);password=(p);Connect Timeout=30;"
Private Const PREDBIpServer As String = "localhost" ' // Predeterminado Default
Private Const PREDBUser As String = "root" ' // Predeterminado Default
Private Const PREDBPass As String = "PYP" '"argetniPYP123" ' // Predeterminado Default
Private Const PREDBIni As String = "information_schema" ' // Predeterminado Default
' // Otros.
Private StrConexion As String
Private MySQLConnectionString As String
' // .||.
Private MyDataAdapter As MySqlDataAdapter
Private MyCommandBuilder As MySqlCommandBuilder
' // .||.
Private DBIpServer As String
Private DBUser As String
Private DBPass As String
Private DBIni As String
Private PrivDataSet As DataSet
Private PrivSqlQuery As String
Private PrivTable As String
Private PrivThisTheardTag As String
Event ErrorEvent(ByVal Ex As Exception, ByVal Cancel As Boolean)
Event Finish()
Public Property StringConection() As String
Get
Return StrConexion
End Get
Set(ByVal value As String)
StrConexion = value
End Set
End Property
Public Property This_Theard_Tag() As String
Get
Return PrivThisTheardTag
End Get
Set(ByVal value As String)
PrivThisTheardTag = value
End Set
End Property
Public Property ServerIP() As String
Get
Return DBIpServer
End Get
Set(ByVal value As String)
DBIpServer = value
End Set
End Property
Public Property ServerDataBase() As String
Get
Return DBIni
End Get
Set(ByVal value As String)
DBIni = value
End Set
End Property
Public Property ServerPassword() As String
Get
Return DBPass
End Get
Set(ByVal value As String)
DBPass = value
End Set
End Property
Public Property ServerUserName() As String
Get
Return DBUser
End Get
Set(ByVal value As String)
DBUser = value
End Set
End Property
Public Function OpenDBMySql(ByVal pServidorIPDNS As String, ByVal pDBuser As String, ByVal pDBPass As String, _
ByVal pBDD As String, ByVal SqlQuery As String, ByVal MySQLConnectionString As String) _
As MySql.Data.MySqlClient.MySqlConnection
Dim MyADOConnection As MySql.Data.MySqlClient.MySqlConnection
If StrConexion = Nothing And MySQLConnectionString = Nothing Then
MySQLConnectionString = PreStrConexion
Else
If MySQLConnectionString = Nothing Then
MySQLConnectionString = StrConexion
End If
End If
If pServidorIPDNS = Nothing And DBIpServer = Nothing Then
pServidorIPDNS = PREDBIpServer
Else
If pServidorIPDNS = Nothing Then
pServidorIPDNS = DBIpServer
End If
End If
If pDBuser = Nothing And DBUser = Nothing Then
pDBuser = PREDBUser
Else
If pDBuser = Nothing Then
pDBuser = DBUser
End If
End If
If (pDBPass = Nothing And DBPass = Nothing) Then
pDBPass = PREDBPass
Else
If pDBPass = Nothing Then
pDBPass = DBPass
End If
End If
If pBDD = Nothing And DBIni = Nothing Then
pBDD = DBDataBaseIni 'PREDBIni
Else
If pBDD = Nothing Then
pBDD = DBIni
End If
End If
MySQLConnectionString = MySQLConnectionString.Replace("(ip)", pServidorIPDNS). _
Replace("(db)", pBDD).Replace("(u)", pDBuser).Replace("(p)", pDBPass)
If Not MyDataAdapter Is Nothing Then
MyDataAdapter = Nothing
End If
If Not MyCommandBuilder Is Nothing Then
MyCommandBuilder = Nothing
End If
Try
MyADOConnection = New MySql.Data.MySqlClient.MySqlConnection(MySQLConnectionString)
MyDataAdapter = New MySqlDataAdapter(SqlQuery, MyADOConnection)
MyCommandBuilder = New MySqlCommandBuilder(MyDataAdapter)
Return MyADOConnection
Catch ex As Exception
Dim Cancel As Boolean
RaiseEvent ErrorEvent(ex, Cancel)
Return Nothing
End Try
End Function
Public Function ExecuteQuery(Optional ByVal SqlQuery As String = "", Optional ByVal Tabla As String = "") As Boolean
Dim MyComandoMysql As New MySqlCommand
Dim MyADOConnection As MySql.Data.MySqlClient.MySqlConnection
If Not SqlQuery = "" Then
PrivSqlQuery = SqlQuery
End If
If Tabla = "" Then
PrivTable = Tabla
End If
MyADOConnection = OpenDBMySql(DBIpServer, DBUser, DBPass, DBIni, PrivSqlQuery, StrConexion)
If Not MyADOConnection Is Nothing Then
Try
MyADOConnection.Open()
MyComandoMysql.Connection = MyADOConnection
MyComandoMysql.CommandType = CommandType.Text
MyComandoMysql.CommandText = PrivSqlQuery
MyComandoMysql.ExecuteNonQuery()
MyADOConnection.Close()
RaiseEvent Finish()
Return True
Catch ex As Exception
Dim Cancel As Boolean
RaiseEvent ErrorEvent(ex, Cancel)
Return False
End Try
Else
RaiseEvent Finish()
Return False
End If
End Function
Public Function GetDataSet(Optional ByVal SqlQuery As String = "", Optional ByVal Tabla As String = "") As DataSet
Dim tmpDataSet As New DataSet
Dim MyComandoMysql As New MySqlCommand
Dim MyADOConnection As MySql.Data.MySqlClient.MySqlConnection
If Not SqlQuery = "" Then
PrivSqlQuery = SqlQuery
End If
If Not Tabla = "" Then
PrivTable = Tabla
End If
MyADOConnection = OpenDBMySql(DBIpServer, DBUser, DBPass, DBIni, PrivSqlQuery, StrConexion)
If Not MyADOConnection Is Nothing Then
Try
MyADOConnection.Open()
MyComandoMysql.Connection = MyADOConnection
MyComandoMysql.CommandType = CommandType.Text
MyComandoMysql.CommandText = PrivSqlQuery
MyComandoMysql.ExecuteNonQuery()
MyDataAdapter.Fill(tmpDataSet, PrivTable)
MyADOConnection.Close()
Catch ex As Exception
Dim Cancel As Boolean
RaiseEvent ErrorEvent(ex, Cancel)
If Cancel Then
RaiseEvent Finish()
Return Nothing
End If
tmpDataSet = Nothing
End Try
PrivDataSet = tmpDataSet
RaiseEvent Finish()
Return tmpDataSet
Else
RaiseEvent Finish()
Return Nothing
End If
End Function
Public Property This_DataBase() As DataSet
Get
Return PrivDataSet
End Get
Set(ByVal value As DataSet)
PrivDataSet = value
End Set
End Property
Public Property This_SqlQuery() As String
Get
Return PrivSqlQuery
End Get
Set(ByVal value As String)
PrivSqlQuery = value
End Set
End Property
Public Property This_Table() As String
Get
Return PrivTable
End Get
Set(ByVal value As String)
PrivTable = value
End Set
End Property
Public Function UpdateFromDataSet(Optional ByVal pDataSet As DataSet = Nothing, _
Optional ByVal SQLQuery As String = "", _
Optional ByVal Tabla As String = "") _
As Boolean
If Not pDataSet Is Nothing Then
PrivDataSet = pDataSet
End If
If Not SQLQuery = "" Then
PrivSqlQuery = SQLQuery
End If
If Not Tabla = "" Then
PrivTable = Tabla
End If
Dim MyADOConnection As MySql.Data.MySqlClient.MySqlConnection
MyADOConnection = OpenDBMySql(DBIpServer, DBUser, DBPass, DBIni, PrivSqlQuery, StrConexion)
If Not MyADOConnection Is Nothing Then
Try
MyADOConnection.Open()
MyDataAdapter.Update(PrivDataSet, PrivTable)
MyADOConnection.Close()
RaiseEvent Finish()
Return True
Catch ex As Exception
Dim Cancel As Boolean
RaiseEvent ErrorEvent(ex, Cancel)
RaiseEvent Finish()
Return False
End Try
Else
RaiseEvent Finish()
Return False
End If
End Function
Public Sub New()
End Sub
End Class
P.D.: Se puede Optimizar xP
Sangriento Infierno Lunar!¡.
Jeje, esta muy interesante tu Clase, la estudiare de cerca.... muchas gracias.