Plsi2019a-6 Adonet-Sinf
Plsi2019a-6 Adonet-Sinf
Plsi2019a-6 Adonet-Sinf
Los procedimientos almacenados son instrucciones SQL que permiten realizar una
tarea repetidamente. Puede crear un procedimiento de una vez y volver a utilizarlo
cualquier número de veces en su programa.
Aparece lo siguiente
Ejecutar con:
Al ejecutar
execute PA_PagosCursos
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -416-
Create procedure Sp_varsalida @num1 float, @num2 float, @resultado float output
As
Begin
Set @resultado=@num1 +@num2
end
Declare @salida float
Exec Sp_Varsalida 20,30 , @salida
Los procedimientos con parámetros dee salida y los de valor de retorno se usan de
forma parecida, es decir, primero se definen, luego se ejecutan y finalmente se lee el
valor devuelto en el parámetro.
Su ejecución
Declare @ValorRetornado int,
@CuentaPagos int
Execute @ValorRetornado=Alumnos1b
@CodAlumno='A1',
@PagosCuenta=@CuentaPagos output
Select @CuentaPagos as '@CuentaPagos'
Select 'ValorRetorno' =@ValorRetornado
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim col As Integer
Dim conn As New SqlConnection
conn.ConnectionString = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\DATOS\ALUMNOS.mdf;Integrated
Security=True;Connect Timeout=30"
conn.Open()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "PA_Alumnos"
Dim rdr As SqlDataReader = cmd.ExecuteReader()
Dim ncampos = rdr.FieldCount
While rdr.Read()
For col = 0 To ncampos - 1
Console.Write("{0}{1}", rdr(col), vbTab)
Next
Console.WriteLine()
End While
Console.ReadLine()
rdr.Close()
conn.Close()
End Sub
End Module
grabar en archivo
Imports System.Data.SqlClient
Imports System.IO
Module Module1
Sub Main()
Dim archivo As StreamWriter
archivo = New StreamWriter("E:\datos\consulta1.txt")
Dim col As Integer
Dim conn As New SqlConnection
conn.ConnectionString = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\DATOS\ALUMNOS.mdf;Integrated
Security=True;Connect Timeout=30"
conn.Open()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT * FROM ALUMNOS"
Dim rdr As SqlDataReader = cmd.ExecuteReader()
Dim ncampos = rdr.FieldCount
While rdr.Read()
For col = 0 To ncampos - 1
archivo.Write("{0}{1}", rdr(col), vbTab)
Next
archivo.WriteLine()
End While
rdr.Close()
conn.Close()
archivo.Close()
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -422-
Console.ReadLine()
End Sub
End Module
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim conn As New SqlConnection
conn.ConnectionString = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\DATOS\ALUMNOS.mdf;Integrated
Security=True;Connect Timeout=30"
conn.Open()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Pagos_Alumno"
Dim CodAlumno1 As SqlParameter = cmd.Parameters.Add("@CodAlumno",
SqlDbType.VarChar, 5)
CodAlumno1.Direction = ParameterDirection.Input
CodAlumno1.Value = "A1"
' create el procedimiento de salida
Dim rdr As SqlDataReader = cmd.ExecuteReader()
Dim nc As Integer = rdr.FieldCount
Dim col As Integer
While rdr.Read()
For col = 0 To nc - 1
Console.Write("{0}{1}", rdr(col), vbTab)
Next
Console.WriteLine()
End While
rdr.Close()
Console.ReadLine()
End Sub
End Module
Imports System.Data.SqlClient
Module Module1
Sub Main()
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -423-
Dim codalu As String
Dim conn As New SqlConnection
conn.ConnectionString = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\DATOS\ALUMNOS.mdf;Integrated
Security=True;Connect Timeout=30"
conn.Open()
Dim cmd As SqlCommand = conn.CreateCommand()
Console.Write(" ingrese codigo del alumno ")
codalu = Console.ReadLine()
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT * FROM PAGOS WHERE CODALUMNO='" &
codalu & "' "
Dim rdr As SqlDataReader = cmd.ExecuteReader()
Dim nc As Integer = rdr.FieldCount
Dim col As Integer
While rdr.Read()
For col = 0 To nc - 1
Console.Write("{0} {1}", rdr(col), vbTab)
Next
Console.WriteLine()
End While
rdr.Close()
Console.ReadLine()
End Sub
End Module
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim cadenaconexion As String = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\DATOS\VENTAS3.mdf;Integrated
Security=True;Connect Timeout=30"
Dim conn As SqlConnection = New SqlConnection(cadenaconexion)
Dim sqlqry As String = "select count(*) from cliente"
Dim Opcion As Integer
Dim codcliente As String
Dim nombrecliente As String
Dim Apellidoscliente As String
Dim Direccioncliente As String
Dim telefonocliente As String
Dim dnicliente As String
Dim comando As SqlCommand = New SqlCommand(sqlqry, conn)
Dim rdr As SqlDataReader
Dim nrocol As Integer
Dim i As Integer
Try
Do
Console.WriteLine(" 1. listar 2. modificar 3 Agregar 4 Eliminar 5 salir ")
Console.Write(" Ingrese opcion ")
Opcion = Console.ReadLine()
Select Case Opcion
Case 1
conn.Open()
Console.WriteLine("Conneccion ABIERTA.")
comando.CommandText = sqlqry
Console.WriteLine(": Numero de clientes {0}",
comando.ExecuteScalar())
comando.CommandText = " SELECT * FROM cliente"
rdr = comando.ExecuteReader
Console.WriteLine("Ejecutando sentencia {0}",
comando.CommandText)
nrocol = rdr.FieldCount
While (rdr.Read)
For i = 0 To nrocol - 1
Console.Write("{0} ", rdr.GetValue(i).ToString.PadRight(10))
Next
Console.WriteLine()
End While
conn.Close()
Case 2
conn.Open()
Console.WriteLine("Ingrese el codigo del cliente a modificar")
codcliente = Console.ReadLine()
Console.WriteLine("Ingrese el NUEVO NOMBRE del cliente a
modificar")
nombrecliente = Console.ReadLine()
Console.WriteLine("Ingrese el Nuevo Apellido a Modificar")
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -425-
Apellidoscliente = Console.ReadLine()
Console.WriteLine("Ingrese la Nueva Direccion a Modificar")
Direccioncliente = Console.ReadLine()
Console.WriteLine("Ingrese el Nuevo Telefono a Modificar")
telefonocliente = Console.ReadLine()
Console.WriteLine("Ingrese el Nuevo Dni ")
dnicliente = Console.ReadLine()
comando.CommandText = " UPDATE CLIENTE SET idcliente= " &
codcliente & _
" , nombre= '" & nombrecliente & "', apellidos= '" & Apellidoscliente
& "',Direccion = '" & _
Direccioncliente & "', telefono= '" & telefonocliente & "', dni='" & dnicliente & "'"
Console.WriteLine("Ejecutando sentencia {0}",
comando.CommandText)
comando.ExecuteNonQuery()
conn.Close()
Case 3
conn.Open()
Console.WriteLine("Ingrese el codigo del cliente a Agregar")
codcliente = Console.ReadLine()
Console.WriteLine("Ingrese el NUEVO NOMBRE del cliente a
agregar")
nombrecliente = Console.ReadLine()
Console.WriteLine("Ingrese el Nuevo Apellido a agregar")
Apellidoscliente = Console.ReadLine()
Console.WriteLine("Ingrese la Nueva Direccion a agregar")
Direccioncliente = Console.ReadLine()
Console.WriteLine("Ingrese el Nuevo Telefono a agregar")
telefonocliente = Console.ReadLine()
Console.WriteLine("Ingrese el Dni a agregar")
dnicliente = Console.ReadLine()
comando.CommandText = _
" INSERT INTO CLIENTE
(Idcliente,nombre,Apellidos,direccion,telefono,dni) values ( '" & _
codcliente & "' , '" & nombrecliente & "' , '" & Apellidoscliente & "' , '" &
Direccioncliente & _
"' ,'" & telefonocliente & "' ,'" & dnicliente & "')"
Console.WriteLine("Ejecutando sentencia {0}",
comando.CommandText)
comando.ExecuteNonQuery()
conn.Close()
Case 4
conn.Open()
Console.WriteLine("Ingrese el codigo del cliente a eliminar")
codcliente = Console.ReadLine()
comando.CommandText = " DELETE FROM CLIENTE WHERE
Idcliente = '" & codcliente & "' "
Console.WriteLine("Ejecutando sentencia {0}",
comando.CommandText)
comando.ExecuteNonQuery()
conn.Close()
End Select
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -426-
Loop Until Opcion = 5
Catch ex As SqlException
Console.WriteLine(ex)
Finally
conn.Close()
Console.WriteLine("Conneccion cerrada.")
End Try
Console.ReadLine()
End Sub
End Module
procedimientos almacenados
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim cadenaconexion As String = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\DATOS\VENTAS3.mdf;Integrated
Security=True;Connect Timeout=30"
Dim conn As SqlConnection = New SqlConnection(cadenaconexion)
Dim Opcion As Integer
Dim codcliente As String
Dim nombrecliente As String
Dim Apellidoscliente As String
Dim Direccioncliente As String
Dim telefonocliente As String
Dim dnicliente As String
Dim comando As SqlCommand = New SqlCommand("", conn)
comando.CommandType = CommandType.StoredProcedure
Dim rdr As SqlDataReader
Dim nrocol As Integer
Dim i As Integer
Try
Do
Console.WriteLine(" 1. listar 2. modificar 3 Agregar 4 Eliminar 5 salir ")
Console.Write(" Ingrese opcion ")
Opcion = Console.ReadLine()
Select Case Opcion
Case 1
conn.Open()
Console.WriteLine("Conneccion ABIERTA.")
comando = New SqlCommand("Mostrar_cliente")
comando.Connection = conn
comando.CommandType = CommandType.StoredProcedure
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -428-
rdr = comando.ExecuteReader
Console.WriteLine("Ejecutando sentencia {0}",
comando.CommandText)
nrocol = rdr.FieldCount
While (rdr.Read)
For i = 0 To nrocol - 1
Console.Write("{0} ", rdr.GetValue(i).ToString.PadRight(8))
Next
Console.WriteLine()
End While
conn.Close()
Case 2
' editar
conn.Open()
comando = New SqlCommand("editar_cliente")
comando.CommandType = CommandType.StoredProcedure
comando.Connection = conn
Console.WriteLine("Ingrese el codigo del cliente a modificar")
codcliente = Console.ReadLine()
Console.WriteLine("Ingrese el NUEVO NOMBRE del cliente a
modificar")
nombrecliente = Console.ReadLine()
Console.WriteLine("Ingrese el Nuevo Apellido a Modificar")
Apellidoscliente = Console.ReadLine()
Console.WriteLine("Ingrese la Nueva Direccion a Modificar")
Direccioncliente = Console.ReadLine()
Console.WriteLine("Ingrese el Nuevo Telefono a Modificar")
telefonocliente = Console.ReadLine()
Console.WriteLine("Ingrese el Nuevo Dni ")
dnicliente = Console.ReadLine()
comando.Parameters.AddWithValue("@idcliente", codcliente) ' enviar
los parametros
comando.Parameters.AddWithValue("@nombre", nombrecliente)
comando.Parameters.AddWithValue("@apellidos", Apellidoscliente)
comando.Parameters.AddWithValue("@direccion", Direccioncliente)
comando.Parameters.AddWithValue("@telefono", telefonocliente)
comando.Parameters.AddWithValue("@dni", dnicliente)
comando.ExecuteNonQuery()
conn.Close()
Case 3
conn.Open()
Console.WriteLine("Ingrese el codigo del cliente a Agregar")
codcliente = Console.ReadLine()
Console.WriteLine("Ingrese el NUEVO NOMBRE del cliente a
agregar")
nombrecliente = Console.ReadLine()
Console.WriteLine("Ingrese el Nuevo Apellido a agregar")
Apellidoscliente = Console.ReadLine()
Console.WriteLine("Ingrese la Nueva Direccion a agregar")
Direccioncliente = Console.ReadLine()
Console.WriteLine("Ingrese el Nuevo Telefono a agregar")
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -429-
telefonocliente = Console.ReadLine()
Console.WriteLine("Ingrese el Dni a agregar")
dnicliente = Console.ReadLine()
comando = New SqlCommand("insertar_cliente")
comando.Connection = conn
comando.CommandType = CommandType.StoredProcedure
' los 6 paramtros
comando.Parameters.AddWithValue("@IdCliente", codcliente)
comando.Parameters.AddWithValue("@nombre", nombrecliente)
comando.Parameters.AddWithValue("@apellidos", Apellidoscliente)
comando.Parameters.AddWithValue("@direccion", Direccioncliente)
comando.Parameters.AddWithValue("@telefono", telefonocliente)
comando.Parameters.AddWithValue("@dni", dnicliente)
Console.WriteLine("Ejecutando sentencia {0}",
comando.CommandText)
comando.ExecuteNonQuery()
conn.Close()
Case 4
conn.Open()
Console.WriteLine("Ingrese el codigo del cliente a eliminar")
codcliente = Console.ReadLine()
comando = New SqlCommand("eliminar_cliente")
comando.CommandType = CommandType.StoredProcedure
comando.Connection = conn ' establece la conexion
comando.Parameters.Add("@idcliente", SqlDbType.NVarChar, 50).Value =
codcliente
comando.ExecuteNonQuery()
conn.Close()
End Select
Loop Until Opcion = 5
Catch ex As SqlException
Console.WriteLine(ex)
Finally
conn.Close()
Console.WriteLine("Conneccion cerrada.")
End Try
Console.ReadLine()
End Sub
End Module
Esta tecnología es una parte del.NET Framework 3.0 (habiendo sido parte del
framework desde la versión 1.0).
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -430-
Arquitectura[editar]
ADO.NET consiste en dos partes primarias:
Data provider[editar]
DataSets[editar]
Los objetos DataSets, son un grupo de clases que describen una simple base de
datos relacional en memoria, fueron la estrella del show en el lanzamiento inicial
(1.0) del Microsoft .NET Framework. Las clases forman una jerarquía de contención:
Classes Description
SqlCommand Ejecuta consultas SQL ,sentencias o procedimientos almacenados
SqlConnection Representa una coneccion hac ia SQL Server database
SqlDataAdapter Representa un puente entre un conjunto de datos y un origen de
datos
SqlDataReader Proporciona una secuencia de datos de sólo avance, de sólo lectura
de los resultados
SqlError Contiene información de errores de SQL Server y advertencias
SqlException Define la excepción que se produce en una advertencia o un error de
SQL Server
SqlParameter Representa un parametro de comando
SqlTransaction Representa una trnsaccion SQL Server
CONECCIO
MODO N COMANDO Tipo devuelve
CONECTAD SQLCONEC SQLCOMMA EXECUTESACAL
O CION ND AR 1 solo valores
EXECUTEDATAR
EADER varios valores
EXECUTENONQ insert,update,
UERY delete
DESCONEC SQLCONEC SQLDATADA
TADO CION PTER
DATASET
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim CadenaConexion As String
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -433-
CadenaConexion = " Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\DATOS\ALUMNOS.mdf;Integrated
Security=True;Connect Timeout=30"
Dim conn As SqlConnection = New SqlConnection(CadenaConexion)
Try
conn.Open()
Console.WriteLine(" Conexion abierta")
'Displaya las propiedades de la conexión
Console.WriteLine("propiedades de la conexion")
Console.WriteLine("cadena de conexion: {0}", conn.ConnectionString)
Console.WriteLine("base de datos: {0}", conn.Database)
Console.WriteLine("fuente de datos: {0}", conn.DataSource)
Console.WriteLine("ServerVersion: {0}", conn.ServerVersion)
Console.WriteLine("State: {0}", conn.State)
Console.WriteLine("WorkstationId: {0}", conn.WorkstationId)
Console.WriteLine("tiempo de conexion: {0}", conn.ConnectionTimeout)
Catch e As SqlException
Console.WriteLine("Error:" & e.ToString)
Finally
conn.Close()
Console.WriteLine("Connection closed.")
End Try
Console.ReadLine()
End Sub
End Module
Imports System.Data.OleDb
Module Module1
Sub Main()
Dim connstring As String
connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=E:\DATOS\alumnos.accdb"
Dim conn As OleDbConnection = New OleDbConnection(connstring)
Try
conn.Open()
Console.WriteLine(" Conexion abierta")
Console.WriteLine("propiedades de la conexion")
Console.WriteLine("cadena de conexion: {0}", conn.ConnectionString)
Console.WriteLine("base de datos: {0}", conn.Database)
Console.WriteLine("fuente de datos: {0}", conn.DataSource)
Console.WriteLine("ServerVersion: {0}", conn.ServerVersion)
Console.WriteLine("State: {0}", conn.State)
Console.WriteLine("Proveedor: {0}", conn.Provider)
Catch e As OleDbException
Console.WriteLine("Error:" & e.ToString)
Finally
conn.Close()
Console.WriteLine("Coneccion cerrada.")
End Try
Console.ReadLine()
End Sub
End Module
Una vez que haya establecido una conexión a la base de datos, que desea empezar
a interactuar con él y hacerlo haciendo algo útil para usted. Puede que necesite
agregar, actualizar, o eliminar algunos datos, o tal vez modificar la base de datos de
alguna otra forma, generalmente mediante la ejecución de una consulta. Cualquiera
que sea la tarea, inevitablemente implicará un comando.
para ejecutar en una base de datos, cada comando debe estar asociado con una
conexión a la base de datos. Para ello, establezca la propiedad de conexión del
comando, y a fin de ahorrar recursos, varios comandos pueden utilizar la misma
conexión.
Los comandos no son usados a menos que se puede ejecutar, Las diferencias entre
estos métodos dependen de los resultados esperados de la instrucción SQL. Las
consultas devuelven filas de datos (conjuntos de resultados), pero las declaraciones
INSERT, UPDATE y DELETE no. Determinar qué método utilizar teniendo en
cuenta los valores devueltos
Imports System.Data.SqlClient
Module Module1
Dim cadenaConexion As String = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\DATOS\ALUMNOS.mdf;Integrated
Security=True;Connect Timeout=30"
Sub Main()
Dim con As SqlConnection = New SqlConnection(cadenaConexion)
Dim cmd As SqlCommand = New SqlCommand("select count(*) from pagos",
con)
Console.WriteLine("Comando creado y conectado .")
Try
con.Open()
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -436-
Console.WriteLine("numero de pagos {0}", cmd.ExecuteScalar())
cmd.CommandText = "select sum(monto) as total from pagos"
Dim total As Single = cmd.ExecuteScalar()
Console.WriteLine("Total de pagos {0} ", total)
cmd.CommandText = "select * from alumnos"
Console.WriteLine("Total de pagos {0} ", cmd.ExecuteScalar())
Catch ex As SqlException
Console.WriteLine(ex)
Finally
con.Close()
Console.WriteLine("Conneccion cerrada.")
End Try
Console.ReadLine()
End Sub
End Module
ExecuteScalar() sólo devuelve la primera fila del resultado y omite el resto.
Un lector de datos es un flujo conectado rápido, sin memoria intermedia, sólo hacia
delante, de sólo lectura que recupera datos por fila. Lee una fila en un momento en
que recorre un conjunto de resultados.
El objeto SqlDataReader tiene un método de lectura que obtiene cada fila a su vez y
un método GetValue que obtiene el valor de una columna de la fila.
Utilizando indizadores ordinales
Imports System.Data.SqlClient
Module Module1
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -437-
Sub Main()
Dim cadenaconexion As String = _
"Data Source=(LocalDB)\v11.0; AttachDbFilename=E:\DATOS\ALUMNOS.mdf;
Integrated Security=True;Connect Timeout=30"
Dim con As SqlConnection = New SqlConnection(cadenaconexion)
Dim nc As Integer
Dim cmd As SqlCommand = New SqlCommand("select * from pagos", con)
Try
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader
nc = rdr.FieldCount
For i = 0 To nc - 1
Console.Write("{0,8} ", rdr.GetName(i))
Next
Console.WriteLine()
While (rdr.Read)
For i = 0 To nc - 1
Console.Write("{0,8} ", rdr(i))
Next
Console.WriteLine()
End While
rdr.Close()
cmd.CommandText = "select sum (monto) as total from pagos "
Dim suma As Single = cmd.ExecuteScalar()
Console.WriteLine("total pagos {0}", suma)
Catch ex As SqlException
Console.WriteLine(ex)
Finally
con.Close()
End Try
Console.ReadLine()
End Sub
End Module3
3
Utilizando los indizadores ordinales.
En el listado 3 modifique
For i = 0 To nc - 1
'Console.Write("{0,8} ", rdr(i))
Console.Write("{0,8} ", rdr.GetValue(i))
Next
Console.WriteLine()
While (rdr.Read)
Console.WriteLine("{0} {1,5} {2,8} {3,8} {4}", rdr("Nro").ToString,
rdr("CodAlumno").ToString, _
rdr("FechaPago").ToString, rdr("Monto"), rdr("codcurso"))
End While
While (rdr.Read)
Console.WriteLine(" {0} {1} {2} {3} {4} ", rdr.GetInt32(0), _
rdr.GetSqlDateTime(1), rdr.GetString(2), rdr.GetDecimal(3),
rdr.GetString(4))
End While
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim cadenaconexion As String = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\Datos\ALUMNOS1.mdf;Integrated
Security=True;Connect Timeout=30"
Dim con As SqlConnection = New SqlConnection(cadenaconexion)
Dim sql As String = "select codalumno ,sum(monto) as total from pagos group
by codalumno"
Dim nc As Integer
Dim cmd As SqlCommand = New SqlCommand(sql, con)
Try
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader
nc = rdr.FieldCount
For i = 0 To nc - 1
Console.Write("{0,8} ", rdr.GetName(i))
Next
Console.WriteLine()
While (rdr.Read)
For i = 0 To nc - 1
Console.Write("{0,8} ", rdr(i))
Next
Console.WriteLine()
End While
Catch ex As SqlException
Console.WriteLine(ex)
Finally
con.Close()
End Try
con.Open()
cmd.CommandText = "select sum (monto) as total from pagos "
Dim suma As Single = cmd.ExecuteScalar()
Console.WriteLine("total pagos {0}", suma)
con.Close()
Console.ReadLine()
End Sub
End Module
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim cadenaconexion As String = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\Datos\ALUMNOS1.mdf;Integrated
Security=True;Connect Timeout=30"
Dim con As SqlConnection = New SqlConnection(cadenaconexion)
Dim nc As Integer
Dim comando1 As SqlCommand = New SqlCommand("select * from pagos",
con)
Try
con.Open()
Console.WriteLine(" consulta {0} ", comando1.CommandText)
Dim rdr1 As SqlDataReader = comando1.ExecuteReader
nc = rdr1.FieldCount
For i = 0 To nc - 1
Console.Write("{0,8} ", rdr1.GetName(i))
Next
Console.WriteLine()
While (rdr1.Read)
For i = 0 To nc - 1
Console.Write("{0,8} ", rdr1(i))
Next
Console.WriteLine()
End While
rdr1.Close()
comando1.CommandText = "select * from alumnos"
Console.WriteLine(" consulta {0} ", comando1.CommandText)
rdr1 = comando1.ExecuteReader
nc = rdr1.FieldCount
For i = 0 To nc - 1
Console.Write("{0,10} ", rdr1.GetName(i))
Next
Console.WriteLine()
While (rdr1.Read)
For i = 0 To nc - 1
Console.Write("{0,10} ", rdr1(i))
Next
Console.WriteLine()
End While
Catch ex As SqlException
Console.WriteLine(ex)
Finally
con.Close()
End Try
Console.ReadLine()
End Sub
End Module
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim cadenaconexion As String = "Data Source=(localdb)\MSSQLLocalDB;Initial
Catalog=ALUMNOS;Integrated Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrit
e;MultiSubnetFailover=False"
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -442-
Dim sql As String = "select nro , codalumno, fechapago , monto, codcurso from
pagos"
Dim conn As SqlConnection = New SqlConnection(cadenaconexion)
Try
conn.Open()
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
Dim rdr As SqlDataReader = cmd.ExecuteReader
'obteniendo nombres de las columnas
Console.WriteLine("Column Name:{0} {1}", rdr.GetName(0).PadRight(20),
rdr.GetName(1))
'obteniendo tipos de datos de las columnas
Console.WriteLine("Data Type:{0} {1}",
rdr.GetDataTypeName(0).PadRight(20), _
rdr.GetDataTypeName(1))
Console.WriteLine()
While (rdr.Read)
' obteniendo valores de las columnas para todas las filas
Console.WriteLine("{0} {1} {2} {3}", rdr.GetInt32(0), rdr.GetString(1),
rdr.GetDateTime(2), rdr.GetDecimal(3))
End While
'obteniendo numero de columnas
Console.WriteLine()
Console.WriteLine("Numbre de ls columnas en la fila {0}", rdr.FieldCount)
'obteniendo información acerca de cada columna
Console.WriteLine(" nombre columna '{0}' indice {1} y el tipo de objeto {2}
", rdr.GetName(0), rdr.GetOrdinal("Nro"), rdr.GetFieldType(0))
Console.WriteLine(" nombre columna ' {0} ' indice {1} y el tipo de objeto {2}
", rdr.GetName(1), rdr.GetOrdinal("CodAlumno"), rdr.GetFieldType(1))
Console.WriteLine(" nombre columna ' {0} ' indice {1} y el tipo de objeto {2}
", rdr.GetName(2), rdr.GetOrdinal("Fechapago"), rdr.GetFieldType(2))
Console.WriteLine(" nombre columna ' {0} ' indice {1} y el tipo de objeto {2}
", rdr.GetName(3), rdr.GetOrdinal("Monto"), rdr.GetFieldType(3))
Console.WriteLine(" nombre columna ' {0} ", rdr.GetDataTypeName(0))
rdr.Close()
Catch e As Exception
Console.WriteLine("Error Occurred:" & e.ToString)
Finally
conn.Close()
End Try
Console.ReadLine()
End Sub
End Module
Sin embargo, aquí es donde generalmente se produce una ligera confusión. Los
objetos de columna de datos no son valores de columna; más bien, son definiciones
de columna que representan y controlan el comportamiento de las columnas
individuales. Puede ser colocadas a través de utilizando un indizador de nombre de
columna, y le puede decir mucho sobre el conjunto de datos.
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim connstring As String = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\Datos\ALUMNOS.mdf;Integrated
Security=True;Connect Timeout=30"
Dim sql As String = "select * from alumnos"
Dim conn As SqlConnection = New SqlConnection(connstring)
Try
conn.Open()
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
Dim rdr As SqlDataReader = cmd.ExecuteReader
'almacenando esquema de alumnos en data table
Dim schema As DataTable = rdr.GetSchemaTable
Dim row As DataRow
For Each row In schema.Rows
Dim col As DataColumn
For Each col In schema.Columns
Console.WriteLine _
((col.ColumnName + " = " + row(col).ToString))
Next col
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -444-
Console.WriteLine("----------------")
Next row
rdr.Close()
Catch e As Exception
Console.WriteLine("Error Occurred:" & e.ToString)
Finally
conn.Close()
End Try
Console.ReadLine()
End Sub
End Module
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim connstring As String = "Data Source=(localdb)\MSSQLLocalDB;Initial
Catalog=ALUMNOS;Integrated Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrit
e;MultiSubnetFailover=False"
Dim sql1 As String = "SELECT * FROM ALUMNOS "
Dim sql2 As String = "SELECT * FROM PAGOS "
Dim sql3 As String = "SELECT * FROM CURSOS "
Dim sql4 As String = "select codalumno ,count(monto) as cant,sum(monto) as
total from pagos group by codalumno"
Dim sql As String = sql1 + sql2 + sql3 + sql4
Dim nc As Integer
Dim conn As SqlConnection = New SqlConnection(connstring)
Try
conn.Open()
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
Dim rdr As SqlDataReader = cmd.ExecuteReader
Dim contador As Integer = 0
Do
Console.WriteLine("TABLA {0} ", contador)
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -445-
nc = rdr.FieldCount
For i = 0 To nc - 1
Console.Write("{0,8} ", rdr.GetName(i))
Next
Console.WriteLine()
While rdr.Read()
' imprime una fila en el tiempo
For i = 0 To nc - 1
Console.Write("{0,8} ", rdr(i))
Next
Console.WriteLine()
End While
Console.WriteLine("".PadLeft(60, "=".ToString))
contador = contador + 1
Loop While rdr.NextResult()
Catch e As Exception
Console.WriteLine("Error Occurred:" & e.ToString)
Finally
conn.Close()
End Try
Console.ReadLine()
End Sub
End Module
1. Insertar un registro
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim cadenaconexion As String = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\Datos\ALUMNOS1.mdf;Integrated
Security=True;Connect Timeout=30"
Dim conn As SqlConnection = New SqlConnection(cadenaconexion)
Dim consulta As String = "insert into alumnos
(Codalumno,nombrealumno,fechanac) values('b9', 'PEPE','1/12/1987')"
Dim comando As SqlCommand = New SqlCommand("", conn)
Try
conn.Open()
comando.CommandText = consulta
Console.WriteLine("Ejecutando sentencia {0}", comando.CommandText)
comando.ExecuteNonQuery()
Catch ex As SqlException
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -446-
Console.WriteLine(ex)
Finally
conn.Close()
Console.WriteLine("Conneccion cerrada.")
End Try
Console.ReadLine()
End Sub
End Module
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim CodAlu As String = "A98"
Dim NombreAlu As String = "MIGUEL"
Dim FechaNac As String = "1/1/2010"
Dim conn As SqlConnection = New SqlConnection("Data Source=(local);Initial
Catalog=ALUMNOS;Integrated Security=True")
Dim sqlqry As String = "select count(*)from alumnos"
'define sentencia insert
Dim sqlins As String = "insert into alumnos
(codalumno,nombrealumno,fechanac)values(@codalu,@nombrealu,@fechanac)"
Dim sqldel As String = "delete from alumnos where Codalumno = @codalu
and nombrealumno = @nombrealu"
'creaando comandos
Dim cmdqry As SqlCommand = New SqlCommand(sqlqry, conn)
Dim cmdnon As SqlCommand = New SqlCommand(sqlins, conn)
cmdnon.Prepare()
'adiciona parametros para el comando
cmdnon.Parameters.Add("@CodAlu", SqlDbType.VarChar, 5)
cmdnon.Parameters.Add("@Nombrealu", SqlDbType.VarChar, 50)
cmdnon.Parameters.Add("@Fechanac", SqlDbType.DateTime)
Try
conn.Open()
'ejecuta la consulta insert y numero de alumnos
Console.WriteLine("ANTES INSERT: Numero de alumnos {0}",
cmdqry.ExecuteScalar())
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -447-
cmdnon.Parameters("@codalu").Value = CodAlu
cmdnon.Parameters("@nombrealu").Value = NombreAlu
cmdnon.Parameters("@FechaNac").Value = FechaNac
Console.WriteLine("Ejecutando sentencia {0}", cmdnon.CommandText)
cmdnon.ExecuteNonQuery()
Console.WriteLine("DESPUES INSERT: Numero de alumnos {0}",
cmdqry.ExecuteScalar())
'execute nonquery to delete alumno
cmdnon.CommandText = sqldel
Console.WriteLine("Executando sentencia {0}", cmdnon.CommandText)
cmdnon.ExecuteNonQuery()
Console.WriteLine(" DESPUES DELETE: Numero de alumnos {0}",
cmdqry.ExecuteScalar())
Catch ex As SqlException
Console.WriteLine(ex)
Finally
conn.Close()
Console.WriteLine("Connecion cerrada.")
End Try
Console.ReadLine()
End Sub
End Module
Una fila de datos representa los datos de una fila. Mediante programación puede
agregar, actualizar o eliminar filas en una tabla de datos. Para acceder a las filas de
una tabla de datos, utilice su propiedad Rows, cuya indizador acepta un índice de
base cero, por ejemplo (donde dt es una tabla de datos):
Lista una consulta dataset con for next y mostrar el elemento de la fila y columna
determinada
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim fila, col As Integer
Dim connstring As String = _
"Data Source=(LocalDB)\v11.0; AttachDbFilename=E:\Datos\ALUMNOS.mdf;
Integrated Security=True;Connect Timeout=30"
Dim sql As String = "SELECT * FROM PAGOS "
Dim conn As SqlConnection = New SqlConnection(connstring)
Try
conn.Open()
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
Dim da As SqlDataAdapter = New SqlDataAdapter(sql, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "pagos")
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -450-
Console.WriteLine("Nombre de la consulta: {0}", sql)
Console.WriteLine("nombre de la tabla: {0}", ds.Tables(0))
Console.WriteLine("valores de los datos")
Dim nfilas As Integer = ds.Tables(0).Rows.Count
Dim ncol As Integer = ds.Tables(0).Columns.Count
For fila = 0 To nfilas - 1
For col = 0 To ncol - 1
Console.Write(" {0}",
ds.Tables(0).Rows(fila).Item(col).ToString.PadRight(10))
Next col
Console.WriteLine()
Next fila
Console.WriteLine("Elemento de fila 2 y col 3 = {0}",
ds.Tables(0).Rows(2).Item(3))
Console.WriteLine("modificamos elemento")
ds.Tables(0).Rows(2).Item(3) = 500
Console.WriteLine("Elemento de fila 2 y col 3 = {0}",
ds.Tables(0).Rows(2).Item(3))
Catch e As Exception
Console.WriteLine("Error Occurred:" & e.ToString)
Finally
conn.Close()
End Try
Console.ReadLine()
End Sub
End Module
Imports System.Data.SqlClient
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -451-
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
Dim fila, col As Integer
Dim connstring As String = "Data Source=(localdb)\MSSQLLocalDB;Initial
Catalog=ALUMNOS;Integrated Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrit
e;MultiSubnetFailover=False"
Dim sql As String = "SELECT * FROM PAGOS "
Dim conn As SqlConnection = New SqlConnection(connstring)
Try
conn.Open()
ListBox1.Items.Clear()
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
Dim da As SqlDataAdapter = New SqlDataAdapter(sql, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "pagos")
ListBox1.Items.Add("Nombre de la consulta: " & sql)
ListBox1.Items.Add("Nombre de la TABLA: " & ds.Tables(0).ToString)
ListBox1.Items.Add("valores de los datos")
Dim cadena As String
Dim nfilas As Integer = ds.Tables(0).Rows.Count
Dim ncol As Integer = ds.Tables(0).Columns.Count
For fila = 0 To nfilas - 1
cadena = ""
For col = 0 To ncol - 1
cadena = cadena +
ds.Tables(0).Rows(fila).Item(col).ToString.PadRight(10)
Next col
ListBox1.Items.Add(cadena)
Next fila
ListBox1.Items.Add("Elemento de fila 2 y col 3 = " &
ds.Tables(0).Rows(2).Item(3))
ListBox1.Items.Add("modificamos elemento")
ds.Tables(0).Rows(2).Item(3) = 500
ListBox1.Items.Add("Elemento de fila 2 y col 3 = " &
ds.Tables(0).Rows(2).Item(3))
Catch eX As Exception
MsgBox("Error Occurred:" & e.ToString)
Finally
conn.Close()
End Try
Console.ReadLine()
End Sub
End Class
MOSTRAR EN DATAGRIDVIEW
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -452-
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load1(sender As Object, e As EventArgs) Handles
MyBase.Load
Dim fila, col As Integer
Dim connstring As String = "Data Source=(localdb)\MSSQLLocalDB;Initial
Catalog=ALUMNOS;Integrated Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrit
e;MultiSubnetFailover=False"
Dim sql As String = "SELECT * FROM PAGOS "
Dim conn As SqlConnection = New SqlConnection(connstring)
Try
conn.Open()
Imports System.Data.SqlClient
Module Module2
Sub Main()
Dim fila, col, k As Integer
Dim connstring As String = "Data Source=(localdb)\MSSQLLocalDB;Initial
Catalog=ALUMNOS;Integrated Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrit
e;MultiSubnetFailover=False"
Dim sql As String = "SELECT * FROM ALUMNOS;SELECT * FROM
PAGOS;SELECT * FROM CURSOS "
Dim conn As SqlConnection = New SqlConnection(connstring)
Try
conn.Open()
Dim da As SqlDataAdapter = New SqlDataAdapter(sql, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "pagos")
ds.Tables(0).TableName = "alumnos"
ds.Tables(1).TableName = "cursos"
ds.Tables(2).TableName = "pagos"
Console.WriteLine("Nombre de la consulta: {0}", sql)
Dim ntablas As Integer = ds.Tables.Count
Dim nfilas As Integer
Dim ncol As Integer
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -454-
For k = 0 To ntablas - 1
Console.WriteLine(" TABLA: {0}", ds.Tables(k))
Console.WriteLine("=============")
nfilas = ds.Tables(k).Rows.Count
ncol = ds.Tables(k).Columns.Count
For i = 0 To ncol - 1
Console.Write(" {0}",
ds.Tables(k).Columns(i).ColumnName.ToString.PadRight(12))
Next i
Console.WriteLine()
For fila = 0 To nfilas - 1
For col = 0 To ncol - 1
Console.Write(" {0}",
ds.Tables(k).Rows(fila).Item(col).ToString.PadRight(12))
Next col
Console.WriteLine()
Next fila
Next k
Console.WriteLine("Elemento de la tabla 1 fila 2 y col 3 = {0}",
ds.Tables(1).Rows(2).Item(3))
Console.WriteLine("modificamos elemento")
ds.Tables(1).Rows(2).Item(3) = 500
Console.WriteLine("Elemento de la tabla 1 fila 2 y col 3 = {0}",
ds.Tables(1).Rows(2).Item(3))
Catch e As Exception
Console.WriteLine("Error Occurred:" & e.ToString)
Finally
conn.Close()
End Try
Console.ReadLine()
End Sub
End Module
Module Module1
Sub Main()
Dim A() As Integer = {10, 20, 30, 40, 50}
Dim i As Integer, nro As Integer
Console.WriteLine(" Mostrando con for next")
For i = 0 To 4
Console.Write(A(i).ToString.PadRight(10))
Next i
Console.WriteLine()
Console.WriteLine(" Mostrando con for each")
For Each nro In A
Console.Write(nro.ToString.PadRight(10))
Next
Console.ReadLine()
End Sub
End Module
Ejemplo 2
Imports System.Data.SqlClient
Module Module1
Sub Main()
' crear un array y rellenarlo con valores
Dim lsColores() As String = {"Azul", "Verde", "Marino", "Violeta"}
Dim lsColor As String
' en cada iteración se obtiene un elemento
' del array lsColores, y se guarda en la variable lsColor
For Each lsColor In lsColores
Console.Write("{0} ", lsColor)
Next
Console.ReadLine()
End Sub
End Module
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -456-
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim connstring As String = " Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\Datos\ALUMNOS.mdf;Integrated
Security=True;Connect Timeout=30"
Dim sql As String = "SELECT * FROM PAGOS "
Dim conn As SqlConnection = New SqlConnection(connstring)
Try
conn.Open()
Dim da As SqlDataAdapter = New SqlDataAdapter(sql, conn)
Dim ds As DataSet = New DataSet
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -457-
da.Fill(ds, "PAGOS")
'displaya los datos
Dim dt As DataTable = ds.Tables("PAGOS")
Dim row As DataRow
For Each row In dt.Rows
Dim col As DataColumn
For Each col In dt.Columns
Console.Write(row(col).ToString.PadRight(12))
Next col
Console.WriteLine()
Next row
Catch e As Exception
Console.WriteLine("Error Occurred:" & e.ToString)
Finally
conn.Close()
End Try
Console.ReadLine()
End Sub
End Module
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim cadenaconexion As String = "Data Source=(localdb)\MSSQLLocalDB;Initial
Catalog=ALUMNOS;Integrated Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrit
e;MultiSubnetFailover=False"
Dim sql1 As String = "select nro, codalumno, Monto from pagos"
Dim con As SqlConnection = New SqlConnection(cadenaconexion)
Try
con.Open()
Dim da As SqlDataAdapter = New SqlDataAdapter
da.SelectCommand = New SqlCommand(sql1, con)
Dim ds As DataSet = New DataSet
da.Fill(ds, "pagos")
' obtiene la coleccion de la tablas
Dim dtc As DataTableCollection = ds.Tables
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -458-
' displaya datos de la primera tablas
Console.WriteLine("Resultados de la consulta {0} ", sql1)
Console.WriteLine(("Nro".PadRight(10) + "Codalumno".PadLeft(10) +
"Monto".PadLeft(10) + ControlChars.Lf))
'' poner filtro para displayar
Dim fl As String = "codalumno = 'A1'"
Dim srt As String = "Nro Desc"
Dim row As DataRow
For Each row In dtc("pagos").Select(fl, srt)
Console.WriteLine("{0} {1} {2} ", row("Nro").ToString.PadLeft(10),
row("CodAlumno").ToString.PadLeft(10), row("Monto").ToString.PadLeft(10))
Next row
Catch e As Exception
Console.WriteLine("Error Occurred:" & e.ToString)
Finally
con.Close()
End Try
Console.ReadLine()
End Sub
End Module
Listar un filtrado ingresando cons codigo por teclado
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim cadenaconexion As String = " Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\Datos\ALUMNOS1.mdf;Integrated
Security=True;Connect Timeout=30"
Dim CADENA As String
Console.Write("INGRESE CODIGO DEL ALUMNO ")
CADENA = Console.ReadLine()
Dim sql1 As String = "select * from pagos WHERE codalumno= '" _
& CADENA & "'ORDER BY MONTO DESC"
Dim con As SqlConnection = New SqlConnection(cadenaconexion)
Try
con.Open()
Dim da As SqlDataAdapter = New SqlDataAdapter
da.SelectCommand = New SqlCommand(sql1, con)
Dim ds As DataSet = New DataSet
da.Fill(ds, "pagos")
Console.WriteLine()
Dim NF As Integer
Dim NC As Integer, fila As Integer, col As Integer
NF = ds.Tables(0).Rows.Count
NC = ds.Tables(0).Columns.Count
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -459-
For col = 0 To NC - 1
Console.Write("{0} ", ds.Tables(0).Columns(col).ColumnName)
Next col
Console.WriteLine()
For fila = 0 To NF - 1
For col = 0 To NC - 1
Console.Write(" {0} ", ds.Tables(0).Rows(fila).Item(col))
Next col
Console.WriteLine()
Next fila
Catch e As Exception
Console.WriteLine("Error Occurred:" & e.ToString)
Finally
con.Close()
End Try
Console.ReadLine()
End Sub
End Module
Mostrar todos los registros de filtrado por codigo del alumno y ordenado por numero
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim connstring As String = " Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\Datos\ALUMNOS1.mdf;Integrated
Security=True;Connect Timeout=30"
Dim sql As String = "select * from alumnos "
Dim conn As SqlConnection = New SqlConnection(connstring)
Try
Dim da As New SqlDataAdapter()
da.SelectCommand = New SqlCommand(sql, conn)
Dim ds As New DataSet()
da.Fill(ds, "alumnos")
Dim dt As DataTable = ds.Tables("alumnos")
' La columna Codalumno debería ser nullable
dt.Columns("codalumno").AllowDBNull = True
dt.Rows(0)("NombreAlumno") = "ALEJANDRO"
' add a row
Dim newRow As DataRow = dt.NewRow()
newRow("Codalumno") = "A9"
newRow("NombreAlumno") = "MARIA"
newRow("FechaNac") = "1/1/1987"
dt.Rows.Add(newRow)
' display rows
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -460-
Dim row As DataRow
For Each row In dt.Rows
Console.WriteLine("{0} {1} {2}", row("codalumno").ToString().PadLeft(5),
row("nombrealumno").ToString().PadRight(20),
row("fechanac").ToString.PadRight(40))
Next row
Catch e As Exception
Console.WriteLine("Error: " + e.ToString)
Finally
conn.Close()
End Try
Console.ReadLine()
End Sub
End Module
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim fila As Integer, col As Integer
Dim cadenaconexion As String = "Data
Source=.\SQLEXPRESS;AttachDbFilename=E:\DATOS\alumnos.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Dim sql1 As String = "select nro, codalumno, Monto from pagos where
codalumno='A1' order by Nro Asc"
Dim con As SqlConnection = New SqlConnection(cadenaconexion)
Try
con.Open()
Dim da As SqlDataAdapter = New SqlDataAdapter
da.SelectCommand = New SqlCommand(sql1, con)
Dim ds As DataSet = New DataSet
da.Fill(ds, "pagos")
For col = 0 To ds.Tables(0).Columns.Count - 1
Console.Write("{0}",
ds.Tables(0).Columns(col).ColumnName.ToString.PadRight(12))
Next
Console.WriteLine()
For fila = 0 To ds.Tables(0).Rows.Count - 1
For col = 0 To ds.Tables(0).Columns.Count - 1
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -461-
Console.Write("{0}",
ds.Tables(0).Rows(fila).Item(col).ToString.PadRight(12))
Next
Console.WriteLine()
Next
Catch e As Exception
Console.WriteLine("Error Occurred:" & e.ToString)
Finally
con.Close()
End Try
Console.ReadLine()
End Sub
End Module
Vamos a actualizar una fila y agregar una fila en una tabla de datos
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim connstring As String = "Data Source=.\sqlexpress;Integrated
Security=True;database=Alumnos"
Dim sql As String = "select * from alumnos "
Dim conn As SqlConnection = New SqlConnection(connstring)
Try
Dim da As New SqlDataAdapter()
da.SelectCommand = New SqlCommand(sql, conn)
Dim ds As New DataSet()
da.Fill(ds, "alumnos")
Dim dt As DataTable = ds.Tables("alumnos")
' La columna Codalumno debería ser nullable
dt.Columns("codalumno").AllowDBNull = True
dt.Rows(0)("NombreAlumno") = "ALEJANDRO"
' add a row
Dim newRow As DataRow = dt.NewRow()
newRow("Codalumno") = "A9"
newRow("NombreAlumno") = "MARIA"
newRow("FechaNac") = "1/1/1987"
dt.Rows.Add(newRow)
' display rows
Dim row As DataRow
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -462-
For Each row In dt.Rows
Console.WriteLine("{0} {1} {2}", row("codalumno").ToString().PadLeft(5),
row("nombrealumno").ToString().PadRight(20),
row("fechanac").ToString.PadRight(40))
Next row
Catch e As Exception
Console.WriteLine("Error: " + e.ToString)
Finally
conn.Close()
End Try
Console.ReadLine()
End Sub
End Module
• UpdateCommand
• InsertCommand
• DeleteCommand
Propiedad UpdateCommand.
Propiedad InsertCommand.
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -463-
El adaptador de datos utiliza la propiedad InsertCommand para insertar filas en una
tabla. Al llamar al método Update, todas las filas en la tabla de datos se buscan y se
propaga a la base de datos.
Propiedad DeleteCommand.
Utilice la propiedad DeleteCommand para ejecutar instrucciones SQL y eliminar.
En este ejemplo, podrá modificar de nuevo para eliminar una fila de la base de
datos.
Constructores de comando.
Utilizando SqlCommandBuilder.
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim connstring As String = " Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\Datos\ALUMNOS1.mdf;Integrated
Security=True;Connect Timeout=30"
Dim qry As String = "select * from alumnos"
Dim conn As SqlConnection = New SqlConnection(connstring)
Try
Dim da As New SqlDataAdapter()
da.SelectCommand = New SqlCommand(qry, conn)
'create command builder
Dim cb As SqlCommandBuilder = New SqlCommandBuilder(da)
Dim ds As New DataSet()
da.Fill(ds, "alumnos")
Dim dt As DataTable = ds.Tables("alumnos")
Dim newRow As DataRow = dt.NewRow()
newRow("codalumno") = "A7"
newRow("nombrealumno") = "MARTIN"
newRow("fechaNac") = "1/1/2007"
dt.Rows.Add(newRow)
Dim row As DataRow
For Each row In dt.Rows
Console.WriteLine("{0} {1} {2}", _
row("codalumno").ToString().PadRight(15), _
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -464-
row("nombrealumno").ToString().PadLeft(20), row("fechanac"))
Next row
da.Update(ds, "alumnos")
Catch e As Exception
Console.WriteLine(("Error: " + e.ToString))
Finally
conn.Close()
End Try
Console.ReadLine()
End Sub
End Module
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim connstring As String = " Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\Datos\ALUMNOS1.mdf;Integrated
Security=True;Connect Timeout=30"
Dim sql As String = "Select * from alumnos"
Dim conn As SqlConnection = New SqlConnection(connstring)
Try
Dim da As SqlDataAdapter = New SqlDataAdapter
da.SelectCommand = New SqlCommand(sql, conn)
conn.Open()
Dim ds As DataSet = New DataSet
da.Fill(ds, "Alumnos")
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -465-
'extract dataset to XML file
ds.WriteXml("E:\DATOS\alumnostable.xml")
Console.WriteLine(" el archivo XML a sido creado")
Catch e As Exception
Console.WriteLine("Error Occurred:" & e.ToString)
Finally
conn.Close()
End Try
Console.ReadLine()
End Sub
End Module
Module Module2
Sub listar()
conn.Open()
Console.WriteLine("Conneccion ABIERTA.")
comando.CommandText = sqlqry
Console.WriteLine(": Numero de alumnos {0}", comando.ExecuteScalar())
comando.CommandText = " SELECT * FROM ALUMNOS"
rdr = comando.ExecuteReader
Console.WriteLine("Ejecutando sentencia {0}", comando.CommandText)
nrocol = rdr.FieldCount
While (rdr.Read)
For i = 0 To nrocol - 1
Console.Write("{0}{1} ", rdr(i), vbTab)
Next
Console.WriteLine()
End While
conn.Close()
End Sub
Sub modificar()
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -467-
conn.Open()
Console.Write("Ingrese el codigo del alumno a modificar :")
codalumno = Console.ReadLine()
Console.Write("Ingrese el NUEVO NOMBRE del alumno a modificar :")
nombrealumno = Console.ReadLine()
Console.Write("Ingrese el NUEVA fecha de nacimiento '1/'1/1988' :")
FechaNac = Console.ReadLine()
comando.CommandText = " UPDATE ALUMNOS SET NOMBREALUMNO ='"
& nombrealumno & " ', FECHANAC=' " & FechaNac & "' WHERE CODALUMNO ='"
& codalumno & " ' "
Console.WriteLine("Ejecutando sentencia {0}", comando.CommandText)
comando.ExecuteNonQuery()
conn.Close()
End Sub
Sub agregar()
conn.Open()
Console.Write("Ingrese el codigo del alumno a Agregar :")
codalumno = Console.ReadLine()
Console.Write("Ingrese NOMBRE del alumno a insertar :")
nombrealumno = Console.ReadLine()
Console.WriteLine("Ingrese fecha de nacimiento '1/'1/1988' ")
FechaNac = Console.ReadLine()
comando.CommandText = " INSERT INTO ALUMNOS
( Codalumno,nombrealumno,fechanac) values ('" & codalumno & "' , '" &
nombrealumno & "' , '" & FechaNac & "')"
Console.WriteLine("Ejecutando sentencia {0}", comando.CommandText)
comando.ExecuteNonQuery()
conn.Close()
End Sub
Sub eliminar()
conn.Open()
Console.Write("Ingrese el codigo del alumno a eliminar :")
codalumno = Console.ReadLine()
comando.CommandText = " DELETE FROM ALUMNOS WHERE
CODALUMNO = '" & codalumno & "' "
Console.WriteLine("Ejecutando sentencia {0}", comando.CommandText)
comando.ExecuteNonQuery()
comando.CommandText = " INSERT INTO ALUMNOS
( Codalumno,nombrealumno,fechanac) values ('" & codalumno & "' , '" &
nombrealumno & "' , '" & FechaNac & "')"
conn.Close()
End Sub
End Module
Imports System.Data.SqlClient
Module Module1
Public cadenaconexion As String = "Data Source=(localdb)\MSSQLLocalDB;Initial
Catalog=ALUMNOS;Integrated Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrit
e;MultiSubnetFailover=False"
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -468-
Public conn As SqlConnection = New SqlConnection(cadenaconexion)
Public sqlqry As String = "select count(*) from alumnos"
Public Opcion As Integer
Public codalumno As String
Public nombrealumno As String
Public FechaNac As String
Public comando As SqlCommand = New SqlCommand(sqlqry, conn)
Public rdr As SqlDataReader
Public nrocol As Integer
Public i As Integer
Sub Main()
Try
Do
Console.WriteLine(" 1. listar 2. modificar 3 Agregar 4 Eliminar 5 salir ")
Console.Write(" Ingrese opcion ")
Opcion = Console.ReadLine()
Select Case Opcion
Case 1
listar()
Case 2
modificar()
Case 3
agregar()
Case 4
eliminar()
End Select
Loop Until Opcion = 5
Catch ex As SqlException
Console.WriteLine(ex)
Finally
conn.Close()
Console.WriteLine("Conneccion cerrada.")
End Try
Console.ReadLine()
End Sub
End Module
Imports System.Data.SqlClient
Public Class Form1
End While
conn.Close()
End Sub
End Class
Imports System.Data.SqlClient
Imports System.IO
Module Module2
Sub Listar()
dt = ds.Tables("alumnos")
Dim fila, col As Integer
nreg = ds.Tables(0).Rows.Count
ncol = ds.Tables(0).Columns.Count
Console.WriteLine(" nombre de la tabla {0} ", dt.TableName)
For col = 0 To ncol - 1
Console.Write(" {0} ", dt.Columns(col).ColumnName)
Next
Console.WriteLine()
For fila = 0 To nreg - 1
For col = 0 To ncol - 1
Console.Write(" {0} ", dt.Rows(fila).Item(col))
Next
Console.WriteLine()
Next
End Sub
Sub basededatos()
Try
da.SelectCommand.CommandText = "SELECT * FROM ALUMNOS "
da.Fill(ds, "ALUMNOS")
dt = ds.Tables("alumnos")
Do
Console.WriteLine(" 1. listar 2. modificar 3 Agregar 4 Eliminar 5 Enviar
Cambios 6 salir ")
Console.WriteLine(" Ingrese opcion ")
Opcion = Console.ReadLine()
Select Case Opcion
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -472-
Case 1
Listar()
Case 2 ' modificar
Console.WriteLine("Ingrese la fila de la tabla a modificar")
Pos = Console.ReadLine
Console.WriteLine("Ingrese codigo de alumno a modifcar ")
codalumno = Console.ReadLine()
Console.WriteLine("Ingrese NOMBRE del alumno a insertar")
nombrealumno = Console.ReadLine()
Console.WriteLine("Ingrese fecha de nacimiento '1/'1/1988'")
FechaNac = Console.ReadLine()
ds.Tables(0).Rows(Pos).Item(0) = codalumno
ds.Tables(0).Rows(Pos).Item(1) = nombrealumno
ds.Tables(0).Rows(Pos).Item(2) = FechaNac
Module Module1
Public maxfilas As Integer = 10
Public maxcol As Integer = 5
Public cadenaconexion As String = " Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\Datos\ALUMNOS.mdf;Integrated
Security=True;Connect Timeout=30"
Public conn As SqlConnection = New SqlConnection(cadenaconexion)
Public Opcion As Integer, Pos As Integer
Public codalumno As String
Public nombrealumno As String
Public FechaNac As String
Public ncol As Integer = 3
Public fila, col As Integer
Public da As SqlDataAdapter = New SqlDataAdapter("", conn)
Public ds As DataSet = New DataSet
Public dt As DataTable = New DataTable
Public filaReg As DataRow
Public nreg As Integer = 10
Public nombrearchivo As String = "E:\datos\alumnos1.txt"
Public A(maxfilas, maxcol) As String
Sub Main()
basededatos()
Console.ReadLine()
End Sub
End Module
Imports System.Data.SqlClient
Public Class Frmdatos
Private Sub MostrarAlumno()
TxtCodalu.Text = ds.Tables(0).Rows(Pos).Item(0)
txtNombreAlu.Text = ds.Tables(0).Rows(Pos).Item(1)
txtFechaNac.Text = ds.Tables(0).Rows(Pos).Item(2)
lblCont.Text = (Pos).ToString & " de " & ds.Tables(0).Rows.Count
End Sub
Private Sub btnListar_Click(sender As Object, e As EventArgs) Handles
BtnListar.Click
da.SelectCommand.CommandText = "SELECT * FROM ALUMNOS "
da.Fill(ds, "ALUMNOS")
DataGridView1.DataSource = ds.Tables(0)
End Sub
Private Sub btnenviar_Click(sender As Object, e As EventArgs) Handles
BtnEnviarCambios.Click
Try
conn.Open()
Dim cbd As New SqlCommandBuilder(da)
da.Update(ds, "alumnos")
conn.Close()
MsgBox("MODIFICACION CORRECTA")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnEliminar_Click(sender As Object, e As EventArgs) Handles
btnEliminar.Click
Try
Dim res As Integer
Pos = DataGridView1.CurrentCell.RowIndex
MostrarAlumno()
' Pos = InputBox("Ingrese la fila a eliminar", "INGRESO", 2)
res = MsgBox("Realmente desea eliminar s/n", MsgBoxStyle.OkCancel)
If res = 1 Then
filaReg = ds.Tables(0).Rows(Pos)
filaReg.Delete()
MsgBox("ELIMINACION CORRECTA")
Else
MsgBox("Eliminacion cancelada ")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnEditar_Click(sender As Object, e As EventArgs) Handles
BtnEditar.Click
' Pos = DataGridView1.CurrentRow.Index
Dim res As Integer
res = MsgBox("Realmente desea modificar s/n", MsgBoxStyle.OkCancel)
If res = 1 Then
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -476-
codalumno = TxtCodalu.Text
nombrealumno = txtNombreAlu.Text
FechaNac = txtFechaNac.Text
ds.Tables(0).Rows(Pos).Item(0) = codalumno
ds.Tables(0).Rows(Pos).Item(1) = nombrealumno
ds.Tables(0).Rows(Pos).Item(2) = FechaNac
MsgBox("Modificacion realizada ")
Else
MsgBox("Modificacion cancelada ")
End If
End Sub
Sub Limpiar()
TxtCodalu.Text = ""
txtNombreAlu.Text = ""
txtFechaNac.Text = ""
TxtCodalu.Focus()
End Sub
Private Sub btnAgregar_Click(sender As Object, e As EventArgs) Handles
BtnAgregar.Click
Try
codalumno = TxtCodalu.Text
nombrealumno = txtNombreAlu.Text
FechaNac = txtFechaNac.Text
filaReg = ds.Tables(0).NewRow()
filaReg(0) = codalumno
filaReg(1) = nombrealumno
filaReg(2) = FechaNac
ds.Tables(0).Rows.Add(filaReg)
MsgBox("SE AGREGO CORRECTAMENTE")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnNuevo_Click(sender As Object, e As EventArgs) Handles
btnNuevo.Click
Limpiar()
End Sub
Private Sub DataGridView1_CellClick(sender As Object, e As
Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Pos = DataGridView1.CurrentRow.Index
MostrarAlumno()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
da.SelectCommand.CommandText = "SELECT * FROM ALUMNOS"
da.Fill(ds, "ALUMNOS")
DataGridView1.DataSource = ds.Tables(0)
End Sub
Private Sub EliminarTodoToolStripMenuItem_Click(sender As Object, e As
EventArgs) Handles MnuEliminarTodo.Click
With ds.Tables(0)
Dim fila As Integer
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -477-
Dim filareg As DataRow
nreg = ds.Tables(0).Rows.Count
For fila = 0 To nreg - 1
filareg = ds.Tables(0).Rows(fila)
filareg.Delete()
Next
MsgBox("Operacion Realizada")
End With
End Sub
Private Sub Simular(sender As Object, e As EventArgs) Handles MnuSimular.Click
Dim i As Integer
With ds.Tables(0)
Dim fila As DataRow
For i = 0 To maxfilas - 1
fila = .NewRow
fila(0) = "A" & i
fila(1) = "Nombre " & i
fila(2) = "1/1/2001"
.Rows.Add(fila)
Next
DataGridView1.DataSource = ds.Tables(0)
MsgBox("Operacion Realizada")
End With
End Sub
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim connstring As String = "Data Source=.\sqlexpress;Integrated
Security=True;database=alumnos"
Dim conn As SqlConnection = New SqlConnection(connstring)
Dim ColTabla As DataColumn
Dim filaTabla As DataRow
Dim tabla As DataTable
Try
conn.Open()
Dim da As SqlDataAdapter = New SqlDataAdapter("", conn)
da.SelectCommand.CommandText = "SELECT * FROM ALUMNOS "
Dim ds As DataSet = New DataSet
da.Fill(ds, "ALUMNOS")
da.SelectCommand.CommandText = "SELECT * FROM PAGOS "
da.Fill(ds, "PAGOS")
da.SelectCommand.CommandText = "SELECT * FROM CURSOS "
da.Fill(ds, "CURSOS")
Console.WriteLine(" nombre de dataset {0} ", ds.DataSetName)
Console.WriteLine(" numero de tablas {0} ", ds.Tables.Count)
For Each tabla In ds.Tables
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -479-
Console.WriteLine(" nombre de la tabla {0} ", tabla.TableName)
For Each ColTabla In tabla.Columns
Console.Write(" {0} ", ColTabla.ColumnName)
Next
Console.WriteLine()
For Each filaTabla In tabla.Rows
For Each ColTabla In tabla.Columns
Console.Write(" {0} ", filaTabla.Item(ColTabla))
Next ColTabla
Console.WriteLine()
Next filaTabla
Next tabla
Catch e As Exception
Console.WriteLine("Error Occurred:" & e.ToString)
Finally
conn.Close()
End Try
Console.ReadLine()
End Sub
End Module
TAREA
Crea una base de datos minimo 3 tablas y practique las Sentancias sql
Las sentencias sql puede practicar con
EXCEL ,Accees ,SQL SERVER 2005,Herramienta de visual basic 2012
Con visual BASIC 2012 modo consola forma conectada y desconectada
Con visual basic 2012 modo formulario
Se tiene una base alumnos llamado empresa que tiene una tabla llamada
trabajadores que tiene la Siguiente estructura
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -480-
Preguntas
Listar los funcionarios
SELECT * FROM TRABAJADORES WHERE TIPO = 3
Promedio de sueldo por sexo
Promedio de sueldo por tipo
Cual es el trabajador mas antiguo
Practica 4
PROCEDIMIENTOS ALMACENADOS(opcional)
Crear un procedimiento almacenado con visual estudio 2008 y ejecutarlo
Crear y ejecutar procedimientos almacenados con SQLserver 2005
Mostrar definiciones de procedimientos almacenados.
Procedimientos con Parámetros de Salida y Valor de Retorno
Trabajar con procedimientos almacenados en VB.NET.
CONOCIENDO A ADO.NET.
Trabajar con el proveedor de datos SQL Server
Listar la tabla alumnos usando proveedor de datos SQLServer
Listar la tabla alumnos usando proveedor de datos OLEDB
Listar la tabla alumnos usando proveedor de datos ODBC
HACIENDO CONEXIONES
escribir un programa muy simple, para abrir y comprobar una conexión:
Mostrar información de conexión.
Conectar a SQL Server Express con el proveedor de datos OLE DB.
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -481-
EJECUTANDO COMANDOS
Crear un comando con un Constructor.
Asociar un comando con una conexión.
Configuración de la propiedad de conexión.
Asignación de texto a un comando.
Configuración de la propiedad CommandText.
Ejecución de comandos
Metodos de ejecución de comandos
obtener un solo valor execute scalar
Ejecutar comandos con varios resultados.
ExecuteReader() la clase SqlDataReader
Ejecutar sentencias de modificación de datos método ExecuteNonQuery.
Uso de parámetros de comando
USANDO DATA READERS
Mostrar un campo , varios campos,etc de una tabla
Utilizando los indizadores ordinales.
Uso de columnas indexado por nombre
Utilizando los métodos de descriptor de acceso con tipo.
Obtener datos sobre datos.
Obtener datos acerca de las tablas.
Imports System.IO
Module Module2
Public Const maxfilas = 10, maxcol = 10
Public A(maxfilas, maxcol) As String
Public nf As Integer = 5
Public nc As Integer = 3
Public nombreArchivo As String
Sub RecuperarMatriz(ByVal nombrearchivo As String, ByRef A(,) As String, ByRef
nf As Integer, ByVal nc As Integer)
Dim srLector As StreamReader
srLector = New StreamReader(nombrearchivo)
Dim fila As Integer = 0, col As Integer
Dim cadena As String = ""
Dim subcadena As String
Dim pos As Integer = 0
Dim inicio As Integer = 1
cadena = srLector.ReadLine()
Do While Not (cadena Is Nothing)
cadena = cadena & Chr(9)
inicio = 1
For col = 0 To nc - 1
pos = InStr(inicio, cadena, Chr(9))
subcadena = Mid(cadena, inicio, pos - inicio)
A(fila, col) = subcadena
inicio = pos + 1
Next
fila = fila + 1
cadena = srLector.ReadLine()
Loop
nf = fila
Console.WriteLine("Archivo {0} leido satisfactoriamente", nombrearchivo)
srLector.Close()
End Sub
End Module
Imports System.IO
Imports System.Data.SqlClient
Public Class Form1
Dim consulta As String
Dim consulta2 As String
Dim dst As New DataSet
Dim dst2 As New DataSet
Dim fila As Integer
Dim CadenaConexion As String = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=E:\Datos1\ALUMNOS.mdf;Integrated
Security=True;Connect Timeout=30"
Dim con As New SqlConnection(CadenaConexion)
Dim dap1 As New SqlDataAdapter("", con)
Dim dap2 As New SqlDataAdapter("", con)
Dim Indice As Integer
Dim CodCurso As String
Dim Nombre As String
Dim Nombrecurso As String
Dim K As Integer
Private Sub CargarArchivoToolStripMenuItem_Click(ByVal sender As Object,
ByVal e As EventArgs) Handles CargarArchivoToolStripMenuItem.Click
OpenFileDialog1.ShowDialog()
nombreArchivo = OpenFileDialog1.FileName
RecuperarMatriz(nombreArchivo, A, nf, nc)
DataGridView1.ColumnCount = nc
DataGridView1.RowCount = nf
MostrarMatriz(A, nf, nc)
End Sub
Sub MostrarMatriz(ByRef A(,) As String, ByRef nf As Integer, ByVal nc As Integer)
For fila = 0 To nf - 1
For col = 0 To nc - 1
If A(fila, col) = Chr(9) Then Continue For
DataGridView1.Rows(fila).Cells(col).Value = A(fila, col)
Next
Next
End Sub
Imports System.Data.SqlClient
Module Module1
Dim Consulta As String
Dim cadena As String = "Data Source=(localdb)\MSSQLLocalDB;Initial
Catalog=ALUMNOS;Integrated Security=True;Connect
Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrit
e;MultiSubnetFailover=False"
Dim conexion As SqlConnection
Dim comando As SqlCommand
Dim nc As Integer
Sub Main()
conexion = New SqlConnection(cadena)
comando = New SqlCommand("", conexion)
conexion.Open()
Do
Console.WriteLine("ingrese consulta")
Consulta = Console.ReadLine
comando.CommandText = Consulta
Imports System.Data.SqlClient
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim cadenaconexion As String = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=D:\DATOS\alumnos.mdf;Integrated
Security=True;Connect Timeout=30"
Dim conn As SqlConnection = New SqlConnection(cadenaconexion)
Dim consulta As String = "insert into pagos
(nro,fechapago,codalumno,monto,codcurso) values(1,'1/12/1987','a1',200,'a4')"
Dim comando As SqlCommand = New SqlCommand("", conn)
Dim r1, r2 As Integer
Dim codalumno As String
Try
Dim fila As Integer
conn.Open()
For fila = 1 To 100
r1 = Int(Rnd() * 6)
r2 = Int(Rnd() * 50) * 10
codalumno = "A" & r1
consulta = "insert into pagos (nro,fechapago,codalumno,monto,codcurso)
values(" _
& fila & ",'1/12/1987','" & codalumno & "'," & r2 & ",'a4')"
comando.CommandText = consulta
Console.WriteLine("Ejecutando sentencia {0}", comando.CommandText)
comando.ExecuteNonQuery()
Next
Catch ex As SqlException
Console.WriteLine(ex)
Finally
conn.Close()
Console.WriteLine("Conneccion cerrada.")
End Try
Console.ReadLine()
End Sub
End Module
GUIA PRACTICAS SI2019A\6 ADO NET\Ismael Véliz Vilca -492-
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim fila As Integer
Dim cadenaconexion As String = "Data
Source=(LocalDB)\v11.0;AttachDbFilename=D:\DATOS\alumnos.mdf;Integrated
Security=True;Connect Timeout=30"
Dim conn As SqlConnection = New SqlConnection(cadenaconexion)
Dim consulta As String = "insert into alumnos
(Codalumno,nombrealumno,fechanac) values('b9', 'PEPE','1/12/1987')"
Dim comando As SqlCommand = New SqlCommand("", conn)
Dim CODALUMNO As String
Dim monto As Single
Try
conn.Open()
For fila = 1 To 100
CODALUMNO = "A" & Int(Rnd() * 6)
monto = Int(Rnd() * 50) * 10
consulta = "insert into pagos (nro,fechapago,Codalumno,monto,codcurso)
values(" & _
fila & ", '12/6/2018','" & CODALUMNO & "'," & monto & ",'C1')"
comando.CommandText = consulta
Console.WriteLine("Ejecutando sentencia {0}", comando.CommandText)
comando.ExecuteNonQuery()
Next
Catch ex As SqlException
Console.WriteLine(ex)
Finally
conn.Close()
Console.WriteLine("Conneccion cerrada.")
End Try
Console.ReadLine()
End Sub
End Module