Conectar / conexión sql server 2005 y c#
Miércoles, 16 de Septiembre de 2009
2 comentarios
CLASE
public class Conexion
{
System.Data.SqlClient.SqlConnection conn;
public Conexion() {
conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString = "Data Source=FAMILIA-2B481F0;Initial Catalog=AdventureWorks;Integrated Security=True";
}
public void abrirConexion() {
try
{
conn.Open();
}
catch (Exception ex) {
MessageBox.Show("No pudo!!");
}
}
public void cerrarConexion() {
try
{
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("No pudo cerrar");
}
}
}
INSERTAR DATOS
public void insertarDatos(DateTime fecha)
{
SqlCommand cm = new SqlCommand();
cm.Connection = conn;
cm.CommandType = System.Data.CommandType.Text;
//cm.CommandText = "INSERT INTO HumanResources.Department(DepartmentID, Name) values(@DepartmentID,@Name)";
//SqlParameter par_id = cm.Parameters.Add("@DepartmentID", SqlDbType.SmallInt);
cm.CommandText = "INSERT INTO HumanResources.Department(Name,GroupName,ModifiedDate)"+
" values(@Name,@GroupName,@ModifiedDate)";
SqlParameter par_name = cm.Parameters.Add("@Name", SqlDbType.NChar);
SqlParameter par_grupo = cm.Parameters.Add("@GroupName", SqlDbType.NChar);
//SqlParameter par_Date = cm.Parameters.Add("@ModifiedDate", SqlDbType.Date);
cm.Parameters.AddWithValue("@ModifiedDate", fecha);
//par_id.Value = 17;
par_name.Value = "depto prueba";
par_grupo.Value = "grupo prueba";
//par_Date.Value = fecha;
cm.ExecuteNonQuery();
}
MODIFICAR DATOS
using System; using System.Data; using System.Data.SqlClient; namespace Client.Chapter_13___ADO.NET { public class UpdatingDataUsingSqlStatements { static void Main(string[] args) { SqlConnection MyConnection = new SqlConnection(@"Data Source=(local); Initial Catalog = CaseManager; Integrated Security=true"); MyConnection.Open(); String MyString = "UPDATE Test SET Contact = 'Lee'"; SqlCommand MyCmd = new SqlCommand(MyString, MyConnection); MyCmd.ExecuteScalar(); MyConnection.Close(); } } }