top of page

EJECUTAR TRANSACCIONES DE SQL SERVER DESDE C#

Código para ejecutar transacciones de SQL SERVER desde código en c#.

using System;
using System.Data.SqlClient;

namespace EjecutorDeQuerys
{
    class EJECUTOR
    {
        static void EJECUTAR()
        {
     
      string usuario = "MyUser";
            string password = "MyPW";
            string server = "190.168.0.X";

            string initialCatalog = "BD_NEW"; 
            string sentencia = "UPDATE DBO.PERSONAS SET EDAD = 21 WHERE NOMBRE = 'PEDRO'";

            SqlConnection con = new SqlConnection("data source =" + server + "; uid =" + usuario + "; PWD =" + password + "; initial catalog = "+ initialCatalog);


            SqlCommand cmd = new SqlCommand();           

            try
            {
               
con.Open();
                cmd = new SqlCommand(sentencia, con);
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.ExecuteNonQuery();
                System.Windows.Forms.MessageBox.Show("Transacción SQL ejecutada");

            }
            catch (Exception e)
            {
             
  System.Windows.Forms.MessageBox.Show("Error al ejecutar la transacción, el mensaje de error es: "+ e.Message);       
            }           

        }
    }
}

bottom of page