Monday, January 19, 2015

C# Execute an DML statement (INSERT,UPDATE or DELETE command)

To execute an action query (INSERT, UPDATE, or DELETE command), use the ExecuteNonQuery method of the DbCommand object.
 string ConnectionInfo = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Blog\Northwind.accdb;";
            string sql;
            int result;

            using (OleDbConnection objConn = new OleDbConnection())
            {
                try
                {
                    objConn.ConnectionString = ConnectionInfo;
                    objConn.Open();

                    using (OleDbCommand objCmd = new OleDbCommand())
                    {
                        sql = @"INSERT INTO Employees(Company,[Last Name],[First Name],[Job Title]) VALUES ('DUMMY Co','Doe','John','Consultant')";
                        objCmd.CommandText = sql;
                        objCmd.Connection = objConn;
                        objCmd.CommandType = CommandType.Text;
                        result = (int)objCmd.ExecuteNonQuery();
                        Console.WriteLine("Just added {0} rows",result);                       
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error occurred");
                    Console.WriteLine(ex.Message);                    
                }
            }

No comments: