Objeto consulta SqlCommand consulta = new SqlCommand(consulta, conexion);
Ejecutar consulta sin retorno. consulta.ExecuteNonQuery();
ODBC CONEXIN Cadena conexin para OdbcConnection() Driver={SQL Server Native Client 10.0};Server=; DataBase=;Trusted_Connection=yes;| UserId=;Password=; Donde Driver depende de la versin de sqlserver instalada.
Abrir conexin objetoconexion.Open()
Objeto consulta OdbcCommand consulta = new OdbcCommand(consulta,conexion)
Ejecutar consulta sin retorno consulta.ExecuteNonQuery();
OLEDB CONEXIN Cadena de conexin para OleDbConnection() "Provider=SQLNCLI10;Data Source=; Initial Catalog=; Integrated Security=SSPI|Uid=;Pwd=; Donde provider depende de la version de sqlserver instalada. Data source es el servidor Initial catalog es la base de datos
Abrir conexion objetoconexion.Open()
Objeto consulta OleDbCommand consulta = new OleDbCommand(consulta, conexion);
Ejecutar consulta sin retorno consulta.ExecuteNonQuery() 7.2. Generar un programa en ambiente consola y otro en ambiente Windows, cada uno con las siguientes especificaciones: Preguntar tipo de conectividad (ODBC, OLEDB, componentes nativos del SQL) Solicitar el nombre del servidor o nombre del DSN, nombre de la instancia, nombre de la BD, usuario y contrasea Realizar la conexin utilizando los parmetros anteriores Mostrar el resultado de una consulta hacia cualquier tabla de la BD Atrapar posibles errores, mostrando el mensaje original
Conexin mediante diferentes medios de conectividad a la base de datos Tec en el servidor ApredaSqlserver tabla Alumno Con autentificacin de windows.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Odbc; using System.Data.OleDb; using System.Data.Sql; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Data.ProviderBase; using System.Windows.Forms; namespace Practica_Grafico{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btncomsultar_Click(object sender, EventArgs e) { if (radsql.Checked == true) { sqlserver(txtserver.Text,txtbase.Text,txttab.Text,txtuser.Text,txtpass.Text,cba.Checked); return; } if (radobdc.Checked == true) { odbc(txtserver.Text,txtbase.Text,txttab.Text,txtuser.Text,txtpass.Text,cba.Checked); return; } else { oledb(txtserver.Text,txtbase.Text,txttab.Text,txtuser.Text,txtpass.Text,cba.Checked); } } void sqlserver(string server,string basedatos, string tabla,string user,string pass,bool intr) { string sconexion = "Server=" + server + "; DataBase=" + basedatos + "; "; if (intr){ sconexion += "Integrated Security=true";} else { sconexion += "User Id=" + user + ";Password=" + pass; } SqlConnection conexion = new SqlConnection(sconexion); try{ conexion.Open(); SqlConnection d = conexion; if (consulta == true) { SqlCommand consultas = new SqlCommand(textBox1.Text, conexion); consultas.ExecuteNonQuery();} SqlCommand select = new SqlCommand("select * from "+tabla, conexion); select.ExecuteNonQuery(); SqlDataAdapter da = new SqlDataAdapter(select); DataSet ds = new DataSet(); da.Fill(ds); dgvresul.DataSource = ds.Tables[0].DefaultView; conexion.Close();} catch (SqlException ex) { switch (ex.Number) {case 18456: MessageBox.Show("Inicio de sesin fallido"); break; default: MessageBox.Show(ex.Message); break; }}
void odbc(string server, string basedatos, string tabla, string user, string pass, bool intr) { string sconexion = "Driver={SQL Server Native Client 10.0};Server=" + server + "; DataBase=" + basedatos + "; "; if (intr) {sconexion += "Trusted_Connection=yes;"; } else { sconexion += "UserId==" + user + ";Password=" + pass; } OdbcConnection conexion = new OdbcConnection(sconexion); try{ conexion.Open(); OdbcConnection d = conexion; if (consulta == true) { OdbcCommand consultas = new OdbcCommand(textBox1.Text, conexion); consultas.ExecuteNonQuery();} OdbcCommand select = new OdbcCommand("select * from "+tabla, conexion); select.ExecuteNonQuery(); OdbcDataAdapter da = new OdbcDataAdapter(select); DataSet ds = new DataSet(); da.Fill(ds); dgvresul.DataSource = ds.Tables[0].DefaultView; conexion.Close();} catch (OdbcException ex) { switch (ex.ErrorCode) {case 20000: MessageBox.Show("Inicio de sesin fallido"); break; default: MessageBox.Show(ex.Message); break; } } }
void oledb(string server, string basedatos, string tabla, string user, string pass, bool intr) { string sconexion = "Provider=SQLNCLI10;Data Source=" + server + "; Initial Catalog=" + basedatos + "; "; if (intr) { sconexion += "Integrated Security=SSPI;"; } else { sconexion += "Uid=" + user + ";Pwd=" + pass; } OleDbConnection conexion = new OleDbConnection(sconexion); try { conexion.Open(); OleDbCommand select = new OleDbCommand("select * from "+tabla, conexion); select.ExecuteNonQuery(); if (consulta == true) { OleDbCommand consultas = new OleDbCommand(textBox1.Text, conexion); consultas.ExecuteNonQuery();} OleDbDataAdapter da = new OleDbDataAdapter(select); DataSet ds = new DataSet(); da.Fill(ds); dgvresul.DataSource = ds.Tables[0].DefaultView; conexion.Close(); } catch (OleDbException ex) { switch (ex.ErrorCode) { case 35000: MessageBox.Show("Inicio de sesin fallido");break; default: MessageBox.Show(ex.Message); break; }}}
Se elije el tipo de conectividad posteriormente se llenan los datos de conexin y procede a hacer la consulta para la tabla.
using System; using System.Collections.Generic; using System.Linq; using System.Data.Odbc; using System.Data.OleDb; using System.Data.Sql; using System.Data.SqlClient; using System.Data.ProviderBase; using System.Text;
namespace Practica_consola{ class Program { static public void capturar_datos(ref string server,ref string database,ref string tabla,ref string user,ref string pass) { Console.WriteLine("SERVIDOR:"); server = Console.ReadLine(); Console.WriteLine("BASE DE DATOS:"); database = Console.ReadLine(); Console.WriteLine("TABLA:"); tabla = Console.ReadLine(); Console.WriteLine("EN CASO DE INICIAR SESION CON WINDOWS DEJAR EN BLANCO."); Console.WriteLine("USER:"); user = Console.ReadLine(); Console.WriteLine("CONSTRASEA:"); pass = Console.ReadLine();Console.WriteLine("Presione una tecla para continuar"); Console.ReadKey(); Console.Clear();} static void sqlserver(){ string server="",tabla="", basedatos="", user="", pass=""; capturar_datos(ref server, ref basedatos,ref tabla,ref user,ref pass); string sconexion = "Server=" + server + "; DataBase=" + basedatos + "; "; if (user==""||pass==""){ sconexion += "Integrated Security=true";} else { sconexion += "User Id=" + user + ";Password=" + pass; } SqlConnection conexion = new SqlConnection(sconexion); try{conexion.Open(); SqlConnection d = conexion; SqlCommand select = new SqlCommand("select * from " + tabla, conexion); select.ExecuteNonQuery(); Console.WriteLine(string.Format(" {0,8} |{1,20} | {2,20} ","NControl","Nombre","Apellidos")); Console.WriteLine("---------------------------------------------------------------------------"); SqlDataReader dr = select.ExecuteReader(); while (dr.Read()) { string apellidos = dr["apaterno"].ToString()+" "+dr["amaterno"].ToString(); Console.WriteLine(string.Format(" {0,8} |{1,20} | {2,20} ", dr["control"], dr["nombre"], apellidos)); } conexion.Close();} catch (SqlException ex) { switch (ex.Number) { case 18456: Console.WriteLine("Inicio de sesin fallido");break; default: Console.WriteLine(ex.Message); break; }}} static void odbc(){ string server="",tabla="", basedatos="", user="", pass=""; capturar_datos(ref server, ref basedatos,ref tabla,ref user,ref pass); string sconexion = "Driver={SQL Server Native Client 10.0};Server=" + server + "; DataBase=" + basedatos + "; "; if (user==""||pass==""){ sconexion += "Trusted_Connection=yes;"; } else { sconexion += "UserId==" + user + ";Password=" + pass; } OdbcConnection conexion = new OdbcConnection(sconexion); try { conexion.Open(); OdbcConnection d = conexion; OdbcCommand select = new OdbcCommand("select * from " + tabla, conexion); select.ExecuteNonQuery(); Console.WriteLine(string.Format(" {0,8} |{1,20} | {2,20} ", "NControl", "Nombre", "Apellidos")); Console.WriteLine("---------------------------------------------------------------------------"); OdbcDataReader dr = select.ExecuteReader(); while (dr.Read()) { string apellidos = dr["apaterno"].ToString() + " " + dr["amaterno"].ToString(); Console.WriteLine(string.Format(" {0,8} |{1,20} | {2,20} ", dr["control"], dr["nombre"], apellidos)); }conexion.Close();} catch (OdbcException ex) { switch (ex.ErrorCode) { case 20000: Console.WriteLine("Inicio de sesin fallido");break; default: Console.WriteLine(ex.Message); break;}}}